2012-02-14 77 views
3

我正在开发具有动态数量的复选框和价格范围的搜索。我需要的映射是这样的路线:MVC 3搜索路线

/过滤/属性/ ATTRIBUTE1,Attribute2,Attribute3 /价格/ 1000-2000

这是做一个好办法吗?我怎样才能做到这一点?

回答

4
routes.MapRoute(
    "FilterRoute", 
    "filter/attributes/{attributes}/price/{pricerange}", 
    new { controller = "Filter", action = "Index" } 
); 

,并在你的索引操作:

public class FilterController: Controller 
{ 
    public ActionResult Index(FilterViewModel model) 
    { 
     ... 
    } 
} 

其中FilterViewModel

public class FilterViewModel 
{ 
    public string Attributes { get; set; } 
    public string PriceRange { get; set; } 
} 

,如果你想你的FilterViewModel看起来像这样:

public class FilterViewModel 
{ 
    public string[] Attributes { get; set; } 
    public decimal? StartPrice { get; set; } 
    public decimal? EndPrice { get; set; } 
} 

你可以写一个客户这个视图模型的tom model binder会解析各种路由令牌。

如果您需要示例,请给我打电话。


UPDATE:

如这里请求是可能被用于路由的值解析到相应的视图模型属性的示例模型粘合剂:

public class FilterViewModelBinder : IModelBinder 
{ 
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     var model = new FilterViewModel(); 
     var attributes = bindingContext.ValueProvider.GetValue("attributes"); 
     var priceRange = bindingContext.ValueProvider.GetValue("pricerange"); 

     if (attributes != null && !string.IsNullOrEmpty(attributes.AttemptedValue)) 
     { 
      model.Attributes = (attributes.AttemptedValue).Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries); 
     } 

     if (priceRange != null && !string.IsNullOrEmpty(priceRange.AttemptedValue)) 
     { 
      var tokens = priceRange.AttemptedValue.Split('-'); 
      if (tokens.Length > 0) 
      { 
       model.StartPrice = GetPrice(tokens[0], bindingContext); 
      } 
      if (tokens.Length > 1) 
      { 
       model.EndPrice = GetPrice(tokens[1], bindingContext); 
      } 
     } 

     return model; 
    } 

    private decimal? GetPrice(string value, ModelBindingContext bindingContext) 
    { 
     if (string.IsNullOrEmpty(value)) 
     { 
      return null; 
     } 

     decimal price; 
     if (decimal.TryParse(value, out price)) 
     { 
      return price; 
     } 

     bindingContext.ModelState.AddModelError("pricerange", string.Format("{0} is an invalid price", value)); 
     return null; 
    } 
} 

这将在Application_Start中被注册Global.asax

ModelBinders.Binders.Add(typeof(FilterViewModel), new FilterViewModelBinder()); 
+0

我从来没有使用过自定义ModelBind呃,你可以发布一个例子或者一个解释如何使用的链接,它会非常有用! :) – Zingui 2012-02-14 11:36:46

+2

@RenanVieira,我用一个例子更新了我的帖子。 – 2012-02-14 13:05:33

+0

哇...非常详细!谢谢! – Zingui 2012-02-14 16:35:19