Asp.net MVC 3搜索路径
我正在开发一个具有动态复选框数量和价格范围的搜索。我需要一条这样的路线:Asp.net MVC 3搜索路径,asp.net,asp.net-mvc-3,c#-4.0,asp.net-mvc-routing,Asp.net,Asp.net Mvc 3,C# 4.0,Asp.net Mvc Routing,我正在开发一个具有动态复选框数量和价格范围的搜索。我需要一条这样的路线: public class FilterViewModel { public string[] Attributes { get; set; } public decimal? StartPrice { get; set; } public decimal? EndPrice { get; set; } } /过滤器/属性/属性1、属性2、属性3/Price/1000-2000 这是一个好方法吗?我
public class FilterViewModel
{
public string[] Attributes { get; set; }
public decimal? StartPrice { get; set; }
public decimal? EndPrice { get; set; }
}
/过滤器/属性/属性1、属性2、属性3/Price/1000-2000
这是一个好方法吗?我怎么走那条路线
routes.MapRoute(
"FilterRoute",
"filter/attributes/{attributes}/price/{pricerange}",
new { controller = "Filter", action = "Index" }
);
在索引操作中:
public class FilterController: Controller
{
public ActionResult Index(FilterViewModel model)
{
...
}
}
其中filtervewmodel
:
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; }
}
您可以为此视图模型编写自定义模型绑定器,该绑定器将解析各种路由令牌
如果你需要一个例子,请告诉我
更新: 根据要求,这里有一个示例模型绑定器,可用于将路由值解析为相应的视图模型属性:
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;
}
}
将在Global.asax中的Application\u Start
中注册:
ModelBinders.Binders.Add(typeof(FilterViewModel), new FilterViewModelBinder());
我从来没有使用过定制的ModelBinder,你能发布一个例子或一个链接来解释如何使用它吗?它将非常有用!:)