2012-02-14 8 views
3

動的なチェックボックスと価格帯を持つ検索を開発しています。これはそれを行うための良い方法ですMVC 3の検索ルート

/フィルター/属性/ ATTRIBUTE1、attribute2の、Attribute3 /価格/ 1000から2000

:私はこのような何かをマップのルートがありますか?どのように私はそのルートを行うことができますか?

答えて

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

とあなたの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モデルバインダー。

例が必要な場合は私にpingしてください。


UPDATE:

ここで要求されるように、対応するビューモデルプロパティにルート値を解析するために使用できるサンプルモデルバインダーは次のとおり

Application_Startに登録されることになる
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

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

私は決してカスタムModelBindを使用しませんでしたあなたが使用方法を説明する例やリンクを投稿できますか?それは非常に便利です! :) – Zingui

+2

@RenanVieira、私は例を使って投稿を更新しました。 –

+0

うわー...非常に詳細!ありがとう! – Zingui