如果Controller's Action没有匹配的参数,RouteValues应该放到哪里?
本文关键字:RouteValues 参数 Controller Action 如果 | 更新日期: 2023-09-27 18:03:20
如果我在其中一个视图中有以下代码:
@Html.Action("Grid", "Product", new { section = SectionType.Product })
这将调用ProductController
的Grid
动作方法,这一切都很好。如果Grid方法定义如下:
public ActionResult Grid(SectionType section) { ... }
然后section
参数将被SectionType.Product
填充,正如我所要求的那样。但是,如果我没有将参数放在方法声明中,如下所示:
public ActionResult Grid() { ... }
然后在视图中设置的section
值似乎完全消失了。它不在Request.Params
,它不在Request.QueryString
,事实上我似乎找不到它在任何地方。
谁能告诉我这个值发生了什么?我可以从任何地方检索它,或者MVC完全丢弃它,如果方法不要求它在参数列表?
您可以通过RouteValueDictionary Values
集合(RequestContext
中的RouteData
)访问从路由中提取的任何参数:
var section = Request.RequestContext.RouteData.Values["section"];
我不确定,如果它是所需的枚举类型(即SectionType
)装进object
,或者只是string
(也装进object
),你需要自己适当地转换为枚举类型。
如果没有可以获取section
参数值的段路由,则将该段路由存储在Request.QueryString
中,并可通过Request.QueryString["section"]
访问。同样,在这种情况下,生成的html应该看起来像...?section=SomeSection
,而在这种情况下,如果你有一个合适的路由,它必须看起来像.../SomeSection
我猜SectionType
是一个enum。如果是,则如果在Action中没有找到匹配的参数,则会发生错误。
// throw exception if you don't pass section value
public ActionResult Grid(SectionType section) { ... }
parameters字典包含一个空的parameter条目不可空类型的'section'"MvcApplication1.Controllers。SectionType' for方法"System.Web.Mvc.ActionResult指数(MvcApplication1.Controllers.SectionType)"MvcApplication1.Controllers.HomeController"。可选参数必须是引用类型、可空类型,或者声明为可选参数。参数名称:parameters
从上面的消息来看,如果在Action中没有找到匹配的参数并且参数是non-nullable
类型,则会发生异常。
如果你像这样改变你的动作:
// nullable SectionType
public ActionResult Grid(SectionType? section) { ... }
或
// default value
public ActionResult Grid(SectionType section = SectionType.Area) { ... }
当section
为nullable
types时,Action将在section
值为null时被调用。当section
有默认值时,动作将被调用,section
的值为null,但在动作中它将使用默认值。