基类访问参数

时间:2010-02-15 11:56:55

标签: asp.net asp.net-mvc

Controller Base类是否可以从操作链接访问参数?如果可以,我如何在基本控制器中访问该参数?

行动链接:

<%=Url.Action("Area_1419", "Home", new { SectionId = 1})%>

基本控制器类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Website.Models;

namespace Website.Controllers
{
    public abstract class CategoriesController : Controller
    {
        public CategoriesDataContext _dataContext = new CategoriesDataContext();

        public CategoriesDataContext DataContext
        {
            get { return _dataContext; }
        }

        public void SectionID()
        {
            int SectionID = Convert.ToInt32(Request.QueryString["SectionID"]);
            ViewData["SectionID"] = SectionID;
        }

        public CategoriesController2()
        {
            //ViewData["Categories"] = from m in _dataContext.Categories where m.Area_ID == SectionID select m;
            //ViewData["Categories"] = from c in DataContext.Categories select c;
        }
    }
}

HomeContoller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Website.Models;
using Website.ActionFilters;

namespace Website.Controllers
{
    [HandleError]
    public class HomeController : CategoriesController
   {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About(int? SectionID)
        {
            //ViewData["Message"] = SectionID;
            return View();
        }

        public ActionResult Area_1419(int SectionID)
        {
            return View();
        }


        public ActionResult Admin()
        {
            return View();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

基类无法访问传递给控制器​​操作的参数,但可以RouteData中获取数据。因此,如果您希望SectionId成为路由的一部分,而不是查询字符串参数,那么您可以这样做:

// Global.asax
routes.MapRoute(
    "WithSection",
    "{sectionId}/{controller}/{action}/{id}",
    new { section = String.Emtpy, action = "index", id = String.Empty }
);

// base controller class
public void SectionID()
{
  int SectionID = Convert.ToInt32(RouteData["SectionID"]);
  ViewData["SectionID"] = SectionID;
}

如果您将SectionId作为查询字符串参数传递,那么您发布的代码应该有效......不是吗?

答案 1 :(得分:0)

通常,您将在BaseController中拥有一个属性,您可以在Filter中设置该属性。

这样的东西
    public override void OnActionExecuting(ActionExecutingContext filterContext)
     {
              ((BaseController)filterContext.Controller).SectionID = "Something";
     }

但请注意,此属性不应在其他过滤器中使用,因为默认情况下无法预测执行顺序。