(转)ASP.NET MVC最佳实践(1)

原文地址:http://space.itpub.net/740297/viewspace-586997

 

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

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

这样的话,您就可以在视图中这样来使用:
1. <a href="<%= Url.Dashboard() %>">Dashboard</a>  
2. <a href="<%= Url.Profile() %>">Profile</a>  
而不是这样:
1. <%= Html.ActionLink("Dashboard", "Dashboard", "Story") %>  
2. <a href="<%= Url.RouteUrl("Profile")%>">Profile</a>  

并且在控制器中我能这么用:
1. return Redirect(Url.Dashboard(StoryListTab.Favorite, OrderBy.CreatedAtAscending, 1))  
而不是这样:
1. return RedirectToAction("Dashboard", "Story", new { tab = StoryListTab.Favorite, rderBy = OrderBy.CreatedAtAscending, page = 1 }); 


 

转载于:https://www.cnblogs.com/fcsh820/archive/2010/11/02/1867089.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值