Action Parameter Naming

家住魔仙堡 提交于 2019-11-30 11:50:12

问题


Using the default route provided, I'm forced to name my parameters "id". That's fine for a lot of my Controller Actions, but I want to use some better variable naming in certain places. Is there some sort of attribute I can use so that I can have more meaningful variable names in my action signatures?

// 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
}

回答1:


Use the [Bind] attribute:

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



回答2:


This still works, your query string will just look like "/Controller/ByAlias?alias=something".




回答3:


You can customize the routes with whatever identifiers you like..

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

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




回答4:


Just because your route uses the name "id" for the ID variable doesn't mean that you have to use the same name in your controller action methods.

For example, given this controller method...

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

...and this action method call from the view...

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

...you can use whatever naming convention you wish for the ID parameter in your controller action methods. All you need to do is resolve the new name to the default, whether it's "id", "alias", or whatever.

The above example should resolve to :

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


来源:https://stackoverflow.com/questions/2030614/action-parameter-naming

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!