首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MVC 3搜索路线

MVC 3搜索路线
EN

Stack Overflow用户
提问于 2012-02-14 10:56:51
回答 1查看 234关注 0票数 3

我正在开发一个具有动态数量的复选框和价格范围的搜索。我需要一条这样的路线:

/Filter/Attribute3/Attribute3 1,Attribute2,Attribute3 3/Price/1000-2000

这是个好办法吗?我怎么走那条路?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-02-14 11:24:11

代码语言:javascript
复制
routes.MapRoute(
    "FilterRoute",
    "filter/attributes/{attributes}/price/{pricerange}",
    new { controller = "Filter", action = "Index" }
);

在你的索引中:

代码语言:javascript
复制
public class FilterController: Controller
{
    public ActionResult Index(FilterViewModel model)
    {
        ...
    }
}

其中FilterViewModel

代码语言:javascript
复制
public class FilterViewModel
{
    public string Attributes { get; set; }
    public string PriceRange { get; set; }
}

如果你想让你的FilterViewModel变成这样:

代码语言:javascript
复制
public class FilterViewModel
{
    public string[] Attributes { get; set; }
    public decimal? StartPrice { get; set; }
    public decimal? EndPrice { get; set; }
}

您可以为这个视图模型编写一个自定义模型绑定器,它将解析各种路由标记。

如果你需要一个例子的话。

更新:

根据请求,这里有一个示例模型绑定,它可以用于将路由值解析为相应的视图模型属性:

代码语言:javascript
复制
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注册。

代码语言:javascript
复制
ModelBinders.Binders.Add(typeof(FilterViewModel), new FilterViewModelBinder());
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9275659

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档