ASP.NET MVC: routing help

五迷三道 提交于 2019-12-11 10:13:30

问题


Consider two methods on the controller CustomerController.cs:

//URL to be http://mysite/Customer/
public ActionResult Index()
{
    return View("ListCustomers");
}

//URL to be http://mysite/Customer/8
public ActionResult View(int id)
{
    return View("ViewCustomer");
}
  • How would you setup your routes to accommodate this requirement?
  • How would you use Html.ActionLink when creating a link to the View page?

回答1:


In global.asax.cs, add following (suppose you use the default mvc visual studio template)

Route.MapRoute("Customer",
    "Customer/{id}",
    new { Controller = "CustomerController", action="View", id="" });

Make sure you put this route before the default route in the template

You then need to modify your controller. For the view,

public ActionResult View(int? id)
{
    if (id == null) 
    {
        return RedirectToAction("Index"); // So that it will list all the customer
    }
    //...The rest follows
}

For your second question, ActionLink is simple.

Html.ActionLink("Link Text", "View", "Customer", new {id=1}, null);


来源:https://stackoverflow.com/questions/2512930/asp-net-mvc-routing-help

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