欢迎大家来我的Bolg作客!在这里我们将为您提供及时全面的IT信息……

ASP.NET MVC最佳实践(1)

1.创建UrlHelper类的扩展方法,生成相对路径URL

请避免将控制器、行为、或者路由名称作为字符串到处传递,创建UrlHelper的扩展方法来封装它们,例如:
UrlHelper类的扩展方法
1 public static class UrlHelperExtension
2 {
3 public static string Home(this UrlHelper helper)
4 {
5 return helper.Content("~/");
6 }
7 public static string SignUp(this UrlHelper helper)
8 {
9 return helper.RouteUrl("Signup");
10 }
11 public static string Dashboard(this UrlHelper helper)
12 {
13 return Dashboard(helper, StoryListTab.Unread);
14 }
15 public static string Dashboard(this UrlHelper helper, StoryListTab tab)
16 {
17 return Dashboard(helper, tab, OrderBy.CreatedAtDescending, 1);
18 }
19 public static string Dashboard(this UrlHelper helper, StoryListTab tab, OrderBy orderBy, int page)
20 {
21 return helper.RouteUrl("Dashboard", new { tab = tab.ToString(), rderBy = orderBy.ToString(), page });
22 }
23 public static string Update(this UrlHelper helper)
24 {
25 return helper.RouteUrl("Update");
26 }
27 public static string Submit(this UrlHelper helper)
28 {
29 return helper.RouteUrl("Submit");
30 }
31 }
32  

这样的话,您就可以在视图中这样来使用:

<a href="<%= Url.Dashboard() %>">Dashboard</a>
<a href="<%= Url.Profile() %>">Profile</a>

而不是这样: 

 

<%= Html.ActionLin ("Dashboard", "Dashboard", "Story") %>
<a href="<%= Url.RouteUrl("Profile")%>">Profile</a>

 

并且在控制器中我能这么用:

 

 

 

 

 

return Redirect
(
Url.Dashboard
(
StoryListTab.Favorite,
OrderBy.CreatedAtAscending,
1
)
);

 

 

而不是这样:

 

return RedirectToAction
(
"Dashboard",
"Story",
new { tab = StoryListTab.Favorite, rderBy = OrderBy.CreatedAtAscending, page = 1 }
);

 

posted @ 2009-12-08 16:55  Cyrus Dai  阅读(395)  评论(0编辑  收藏  举报
Copyright ? 戴超 2008-10-30---9595-95-95