代码之家  ›  专栏  ›  技术社区  ›  Langdon

动作参数命名

  •  30
  • Langdon  · 技术社区  · 16 年前

    使用提供的默认路由,我不得不将参数命名为“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
    }
    
    4 回复  |  直到 12 年前
        1
  •  48
  •   Levi    16 年前

    使用[绑定]属性:

    public ActionResult ByAlias([Bind(Prefix = "id")] string alias) {
        // your code here
    }
    
        2
  •  0
  •   Chris Shaffer    16 年前

    这仍然有效,您的查询字符串看起来就像“/controller/byalias”?别名=某物”。

        3
  •  0
  •   curtisk    16 年前

    您可以使用您喜欢的任何标识符自定义路由。

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

    编辑: Here's an overview from the ASP.NET site

        4
  •  0
  •   Neil T.    16 年前

    仅仅因为路由对id变量使用了名称“id”,并不意味着您必须在控制器操作方法中使用相同的名称。

    例如,给出了这种控制器方法…

    public Controller MailerController
    {
        public ActionResult Details(int mailerID)
        {
            ...
            return View(new { id = mailerID });
        }
    }
    

    …并且此操作方法从视图调用…

    <%= Html.ActionLink("More Info", "Details", new { mailerID = 7 }) %>
    

    …您可以对控制器操作方法中的id参数使用您希望的任何命名约定。您所需要做的就是将新名称解析为默认名称,无论是“id”、“alias”还是其他什么名称。

    上述示例应解决以下问题:

    <a href="/Mailer/Details/7">More Info</a>