将简单的json绑定到MVC Form Collection

时间:2012-06-04 18:47:46

标签: c# json asp.net-mvc-3 data-binding knockout.js

我试图将一个简单的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();
    }
杰森:

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

我试图找出如何自动将json的简单键值对绑定到表单集合。我不想创建一个绑定json的对象,因为我需要更灵活地根据其他信息动态创建它们。

我是如何做到的?

非常感谢,

马修

1 个答案:

答案 0 :(得分:1)

您似乎需要创建一个自定义绑定器,它会自动将数据绑定到IDictionary。

The Binder

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);
    }
}

您应该在Global for IDictionary&lt;&gt;中注册活页夹类型。还有其他方法可以注册粘合剂。

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

最后,您应该可以使用IDictionary&lt;&gt;。这将绑定到您将从ajax传递的所有属性

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