如果我没听错的话。用户 ID 是“mhis/001”,年份是 2012,那么你想使用这样的 URL:
http://localhost:59025/User/mhis/001/2012
Global.asax - 定义路线:
routes.MapRoute(
"UserDetails", // Route Name
"User/{idpart1}/{idpart2}/{year}", // URL with parameters
new { controller = "User", action = "Details", year= UrlParameter.Optional} // Parameter defaults
);
“year”参数设置为可选,因此如果用户输入http://localhost:59025/User/mhis/001/2012
,则年份将为 2012,如果不输入任何内容,则年份将为空。
一个虚拟用户类:
public class User
{
public String Id { get; set; }
public String Name { get; set; }
/// <summary>
/// just a helper to get the first part of the userID
/// </summary>
public string IDPart1 { get { return Id.Split('/')[0]; } }
/// <summary>
/// just a helper to get the second part of the userID
/// </summary>
public string IDPart2 { get { return Id.Split('/')[1]; } }
}
向 User 类添加了两个帮助器属性,将用户名分开(IDPart1,IDPart2),因此在视图中更易于使用
具有虚拟用户列表的控制器:
public class UserController : Controller
{
/// <summary>
/// user list...
/// </summary>
List<User> _users = new List<User> {
new User{ Id="mhis/001", Name="John Smith"},
new User{ Id="mhis/002", Name="Some Body Else"}
};
/// <summary>
/// This is actually a user list, but...
/// </summary>
/// <returns></returns>
public ActionResult Index()
{
return View(_users);
}
public ActionResult Details(string idpart1, string idpart2, int? year)
{
//do what you have to do with the year...
ViewBag.year = year;
string realUserID = String.Format(@"{0}/{1}", idpart1, idpart2);
var user = _users.FirstOrDefault(u => u.Id == realUserID);
return View(user);
}
}
列表视图:
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.ActionLink("Details", "Details", new { idpart1 = item.IDPart1, idpart2 = item.IDPart2 })
</td>
</tr>
}
有趣的部分是:@Html.ActionLink("Details", "Details", new { idpart1 = item.IDPart1, idpart2 = item.IDPart2 })
,你得到你想要的。
详情查看:
@model MvcApplication1.Controllers.User
@{
ViewBag.Title = "Details";
}
@if(Model != null) {
<h2>Details</h2>
<fieldset>
<legend>User</legend>
The year is: "@ViewBag.year"
<div class="display-label">Name</div>
<div class="display-field">
@Html.DisplayFor(model => model.Name)
</div>
</fieldset>
<p>@Html.ActionLink("Back to List", "Index")</p>
} else {//this should be handled in the controller...
<h2>User not found!</h2>
}