2014-03-28 55 views
3

我控制器的方法是這樣的:是否有可能從查詢字符串中獲取字典?

public ActionResult SomeMethod(Dictionary<int, string> model) 
{ 

} 

是否有可能調用此方法並填充「模式」僅使用查詢字符串?我的意思是,打字如下:

ControllerName/SomeMethod?model.0=someText&model.1=someOtherText 

在我們的瀏覽器地址欄中。可能嗎?

編輯:

這樣看來,我的問題被誤解了 - 我想查詢字符串綁定,從而使字典方法的參數自動填充。換句話說 - 我不想手動創建我的方法裏面的字典,但有一些automathic .NET粘結劑做到這一點構成了我,這樣我就可以訪問它馬上像這樣:

public ActionResult SomeMethod(Dictionary<int, string> model) 
{ 
    var a = model[SomeKey]; 
} 

是否有自動粘合劑,足夠聰明地做到這一點?

+0

看看這個:http://stackoverflow.com/questions/2375372/is-ther e-a-way-to-get-all-the-querystring-name-value-pairs-into-a-collection – Portekoi

+0

@max也沒有真正提高可讀性。 – CodeCaster

+0

@CodeCaster它比以前更好,因爲它看起來不是問題的一部分,而更像是其他人如何實現它的例子。你現在做的更好。 – Max

回答

1

已經有一個字典 - 它被稱爲Request.QueryString。

+0

請參閱我的編輯。 – user2384366

1

嘗試自定義模型粘合劑

 public class QueryStringToDictionaryBinder: IModelBinder 
{ 
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     var collection = controllerContext.HttpContext.Request.QueryString; 
     var modelKeys = 
      collection.AllKeys.Where(
       m => m.StartsWith(bindingContext.ModelName)); 
     var dictionary = new Dictionary<int, string>(); 

     foreach (string key in modelKeys) 
     { 
      var splits = key.Split(new[]{'.'}, StringSplitOptions.RemoveEmptyEntries); 
      int nummericKey = -1; 
      if(splits.Count() > 1) 
      { 
       var tempKey = splits[1]; 
       if(int.TryParse(tempKey, out nummericKey)) 
       { 
        dictionary.Add(nummericKey, collection[key]);  
       } 
      }     
     } 

     return dictionary; 
    } 
} 

在控制器動作用它的型號

 public ActionResult SomeMethod(
     [ModelBinder(typeof(QueryStringToDictionaryBinder))] 
     Dictionary<int, string> model) 
    { 

     //return Content("Test"); 
    } 
1

更多具體到mvc模型綁定是爲了解釋克拉查詢字符串作爲

/somemethod?model[0].Key=1 &模型[0]。價值=一個&模型[1]。重點= 2 &模型[1]。價值=兩個

定製綁定將只需按照DefaultModelBinder

public class QueryStringToDictionary<TKey, TValue> : IModelBinder 
{ 
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     var modelBindingContext = new ModelBindingContext 
     { 

      ModelName = bindingContext.ModelName, 
      ModelMetadata = new ModelMetadata(new EmptyModelMetadataProvider(), null, 
       null, typeof(Dictionary<TKey, TValue>), bindingContext.ModelName), 
      ValueProvider = new QueryStringValueProvider(controllerContext) 
     }; 

     var temp = new DefaultModelBinder().BindModel(controllerContext, modelBindingContext); 

     return temp; 
    } 
} 

應用定製的模型綁定模型作爲

 public ActionResult SomeMethod(
     [ModelBinder(typeof(QueryStringToDictionary<int, string>))] Dictionary<int, string> model) 
    { 
     // var a = model[SomeKey]; 
     return Content("Test"); 
    } 
相關問題