将简单的 json 绑定到 MVC 表单集合

本文关键字:MVC 表单 集合 绑定 简单 json | 更新日期: 2023-09-27 18:36:11

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

想法是我该怎么做?

任何事情都非常感谢,

马修

将简单的 json 绑定到 MVC 表单集合

您似乎需要创建一个自定义绑定器,该绑定器将自动将数据绑定到 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
    }