操作参数命名

Lan*_*don 30 c# asp.net-mvc asp.net-mvc-routing

使用提供的默认路由,我被迫将参数命名为"id".这对我的许多控制器动作来说都很好,但我想在某些地方使用一些更好的变量命名.我可以使用某种属性,以便在操作签名中包含更有意义的变量名称吗?

// Default Route:
routes.MapRoute(
  "Default",                                              // Route name
  "{controller}/{action}/{id}",                           // URL with parameters
  new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
);

// Action Signature:
public ActionResult ByAlias(string alias)
{
  // Because the route specifies "id" and this action takes an "alias", nothing is bound
}
Run Code Online (Sandbox Code Playgroud)

Lev*_*evi 48

使用[Bind]属性:

public ActionResult ByAlias([Bind(Prefix = "id")] string alias) {
    // your code here
}
Run Code Online (Sandbox Code Playgroud)

  • 这是我发现的使用 Bind 的最好例子!有没有办法也可以在模型属性上进行这项工作?即,代替具有字符串参数的方法签名,它具有作为参数的类,该类具有如下所示的属性:`[Bind(Prefix = "id")]string Alias {get; 设置;}`?该示例无法编译......我将如何修改它以编译(并且也可以工作)? (2认同)