2012-06-04 49 views
0

我試圖綁定一個簡單的JSON對象(只是鍵值對)的MVC形式收集或類似的東西綁定簡單的JSON到MVC表單集中

的JavaScript:

function CMSModel() { 
    var self = this; 

    self.Enable = ko.observable(true); 
    self.CMSAddress = ko.observable(); 
    self.CMSAddressExtension = ko.observable(); 
    self.Username = ko.observable(); 
    self.Password = ko.observable(); 
    self.Protocol = ko.observable(); 
    self.Port = ko.observable(); 
    self.Interval = ko.observable(); 
    self.Area = "CMS"; 

    self.SubmitCMS = function() { 

     //Validate numbers 

     $.ajax({ 
      url: "/config/@Model.Model/" + self.Area, 
      contentType: "application/json", 
      type: "POST", 
      success: function (result) { 
       alert(result); 
      }, 
      error: function (result) { 
       alert(result); 
      }, 
      data: ko.toJSON(self) 

     }); 
    } 
} 

而且這是我想在MVC方面的內容:

public ActionResult CMS(FormCollection fc) 
    { 
     return View(); 
    } 

JSON:

{"CMSAddress":"asdf","CMSAddressExtension":"asf","Username":"asdf","Password":"asdf","Protocol":"HTTP","Port":"123","Interval":"123","Area":"CMS"} 

我想弄清楚如何自動綁定一個簡單的鍵值對的JSON到表單集合。我不想創建一個綁定json的對象,因爲我需要更靈活地根據其他信息動態創建它們。

想法,我該如何做到這一點?

什麼是極大的讚賞,

馬修

回答

1

看來你需要創建一個自定義的粘合劑,將數據自動綁定到IDictionary的。

的活頁夾

public class DictionaryModelBinder : DefaultModelBinder 
{ 
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     //get the posted JSON 
     var request = controllerContext.HttpContext.Request; 
     var jsonStringData = new StreamReader(request.InputStream).ReadToEnd(); 
     //use newtonsoft.json to deserialise the json into IDictionary 
     return JsonConvert.DeserializeObject<IDictionary<string,string>>(jsonStringData); 
    } 
} 

你應該登記在全球的粘合劑的IDictionary <>類型。還有其他方法來註冊粘合劑。

protected void Application_Start() 
{ 
    ...other logic 
    ModelBinders.Binders.Add(typeof(IDictionary<string, string>), 
           new DictionaryModelBinder()); 
    ...other logic 
}  

最後,你應該可以使用IDictionary <>。這將被綁定到你將通過ajax的所有屬性

public ActionResult YourAction(IDictionary<string, string> values) 
    { 
     ... your logic here 
    } 
+0

這很好,但由於某種原因,它沒有正確綁定到ko.toJSON(self)。數據看起來都一樣(都是有效的JSON),但由於某種原因,它不會變成鍵值對像手動鍵入它 作品有: {「cms_address」:self.CMSAddress} 不一起工作: ko.toJSON(self)導致 {「CMSAddress」:「asdf」,「CMSAddressExtension」:「asdf」,「用戶名」:「asdf」,「密碼」:「asdf」,「協議」 :「HTTP」,「端口」:「asdf」,「間隔」:「asdf」,「區域」:「CMS」} – Matthew

+0

哦,是的,我會更新答案 – workoholic

+0

非常感謝你! – Matthew