开发者

ASP.NET MVC: routing help

开发者 https://www.devze.com 2022-12-24 19:20 出处:网络
Consider twomethods on the controller CustomerController.cs: //URL to be http://mysite/Customer/ public ActionResult Index()

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 route开发者_如何学Cs to accommodate this requirement?
  • How would you use Html.ActionLink when creating a link to the View page?


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号