1.分页扩展方法
1.1定义
1 public static MvcHtmlString PageLinks(this HtmlHelper html,
2 PagingInfo pagingInfo,
3 Func<int, string> pageUrl) {
4 StringBuilder result = new StringBuilder();
5 for (int i = 1; i <= pagingInfo.TotalPages; i++) {
6 TagBuilder tag = new TagBuilder("a"); // Construct an <a> tag
7 tag.MergeAttribute("href", pageUrl(i));
8 tag.InnerHtml = i.ToString();
9 if (i == pagingInfo.CurrentPage)
10 tag.AddCssClass("selected");
11 result.Append(tag.ToString());
12 }
13 return MvcHtmlString.Create(result.ToString());
14 }
public class PagingInfo {
public int TotalItems { get; set; }
public int ItemsPerPage { get; set; }
public int CurrentPage { get; set; }
public int TotalPages {
get { return (int)Math.Ceiling((decimal)TotalItems / ItemsPerPage); }
}
}
1.2使用配置以及调用
1 <system.web.webPages.razor>
2 <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc,
3 Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
4 <pages pageBaseType="System.Web.Mvc.WebViewPage">
5 <namespaces>
6 <add namespace="System.Web.Mvc" />
7 <add namespace="System.Web.Mvc.Ajax" />
8 <add namespace="System.Web.Mvc.Html" />
9 <add namespace="System.Web.Routing" />
10 <add namespace="这里加入您的扩展类的类名,这样在cshtml页面就不用导入命名空间了"/>
11 </namespaces>
1 <div class="pager">
2 @Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new {page = x}))
3 </div>
2.模型绑定到购物车229
public class CartModelBinder : IModelBinder {
private const string sessionKey = "Cart";
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext) {
// get the Cart from the session
Cart cart = (Cart)controllerContext.HttpContext.Session[sessionKey];
// create the Cart if there wasn't one in the session data
if (cart == null) {
cart = new Cart();
controllerContext.HttpContext.Session[sessionKey] = cart;
}
// return the cart
return cart;
}
}
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
ModelBinders.Binders.Add(typeof(Cart), new CartModelBinder());
}
public RedirectToRouteResult AddToCart(Cart cart, int productId, string returnUrl) {
Product product = repository.Products
.FirstOrDefault(p => p.ProductID == productId);
if (product != null) {
cart.AddItem(product, 1);
}
return RedirectToAction("Index", new { returnUrl });
}
定义可变长度的路由
1 public static void RegisterRoutes(RouteCollection routes) { routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
2
3 new { controller = "Home", action = "Index", id = UrlParameter.Optional }
4 );
5 }
public static void RegisterRoutes(RouteCollection routes) {
routes.MapRoute("MyRoute",
"{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "URLsAndRoutes.Controllers"}
);
}
让路由只使用我们定义的命名空间,不再搜索其他命名空间
public static void RegisterRoutes(RouteCollection routes) {
Route myRoute = routes.MapRoute("AddContollerRoute",
"Home/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "AdditionalControllers" }
);
myRoute.DataTokens["UseNamespaceFallback"] = false;
}
使用正则表达式控制路由
public static void RegisterRoutes(RouteCollection routes) {
routes.MapRoute(
"MyRoute",
"{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { controller = "^H.*", action = "^Index$|^About$"},
new[] { "URLsAndRoutes.Controllers"});
}
public static void RegisterRoutes(RouteCollection routes) {
routes.MapRoute(
"MyRoute",
"{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { controller = "^H.*", action = "Index|About",
httpMethod = new HttpMethodConstraint("GET", "POST") },
new[] { "URLsAndRoutes.Controllers" }
);
}
自定义路由限制,使用IRouteConstraint
namespace URLsAndRoutes.Infrastructure {
public class UserAgentConstraint : IRouteConstraint
{
private string requiredUserAgent;
public UserAgentConstraint(string agentParam)
{
requiredUserAgent = agentParam;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
return httpContext.Request.UserAgent != null
&& httpContext.Request.UserAgent.Contains(requiredUserAgent);
}
}
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"MyRoute",
"{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new {
controller = "^H.*", action = "Index|About",
httpMethod = new HttpMethodConstraint("GET", "POST"),
customConstraint = new UserAgentConstraint("IE")
},
new[] { "URLsAndRoutes.Controllers" }
);
}
允许路由到静态html文件
public static void RegisterRoutes(RouteCollection routes) {
routes.RouteExistingFiles = true;
routes.MapRoute(
"MyRoute",
"{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new {
controller = "^H.*", action = "Index|About",
httpMethod = new HttpMethodConstraint("GET", "POST"),
customConstraint = new UserAgentConstraint("IE")
},
new[] { "URLsAndRoutes.Controllers" }
);
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.RouteExistingFiles = true;
routes.MapRoute(
"DiskFile",
"Content/StaticContent.html",
new {
controller = "Account", action = "LogOn",
},
new {
customConstraint = new UserAgentConstraint("IE")
}
);
routes.IgnoreRoute("Content/{filename}.html");
routes.MapRoute("", "{controller}/{action}");
routes.MapRoute("MyRoute",
"{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new {
controller = "^H.*", action = "Index|About",
httpMethod = new HttpMethodConstraint("GET", "POST"),
customConstraint = new UserAgentConstraint("IE")
},
new[] { "URLsAndRoutes.Controllers" }
);
}