您的位置:首页 > 编程语言 > ASP

ASP.NET MVC最佳实践(1)

2009-12-08 16:55 239 查看

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

请避免将控制器、行为、或者路由名称作为字符串到处传递,创建UrlHelper的扩展方法来封装它们,例如:

UrlHelper类的扩展方法

public static class UrlHelperExtension
{
public static string Home(this UrlHelper helper)
{
return helper.Content("~/");
}
public static string SignUp(this UrlHelper helper)
{
return helper.RouteUrl("Signup");
}
public static string Dashboard(this UrlHelper helper)
{
return Dashboard(helper, StoryListTab.Unread);
}
public static string Dashboard(this UrlHelper helper, StoryListTab tab)
{
return Dashboard(helper, tab, OrderBy.CreatedAtDescending, 1);
}
public static string Dashboard(this UrlHelper helper, StoryListTab tab, OrderBy orderBy, int page)
{
return helper.RouteUrl("Dashboard", new { tab = tab.ToString(), rderBy = orderBy.ToString(), page });
}
public static string Update(this UrlHelper helper)
{
return helper.RouteUrl("Update");
}
public static string Submit(this UrlHelper helper)
{
return helper.RouteUrl("Submit");
}
}


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

<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 }
);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: