ASP.NET MVC:路由帮助 [英] ASP.NET MVC: routing help
本文介绍了ASP.NET MVC:路由帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑控制器 CustomerController.cs
的两种方法:
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");
}
- 你将如何设置你的路线,以适应这一要求?
- 您将如何创建一个链接视图页? 在当前使用Html.ActionLink
- How would you setup your routes to accommodate this requirement?
- How would you use Html.ActionLink when creating a link to the View page?
推荐答案
在的global.asax.cs,添加如下(假设你使用默认的MVC的Visual Studio模板)
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
}
有关你的第二个问题,ActionLink的很简单。
For your second question, ActionLink is simple.
Html.ActionLink("Link Text", "View", "Customer", new {id=1}, null);
这篇关于ASP.NET MVC:路由帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文