0

我正在尝试将一个简单的 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,因为我需要更灵活地根据其他一些信息动态创建它们。

想我怎么能做到这一点?

任何事情都非常感谢,

马修

4

1 回答 1

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

您应该在 Global 中为 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
    }
于 2012-06-04T19:35:02.153 回答