I’m trying to bind a simple json object (just key value pairs) to an MVC form collection or something of the sort
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)
});
}
}
And this is what I would like on the MVC side:
public ActionResult CMS(FormCollection fc)
{
return View();
}
Json:
{"CMSAddress":"asdf","CMSAddressExtension":"asf","Username":"asdf","Password":"asdf","Protocol":"HTTP","Port":"123","Interval":"123","Area":"CMS"}
I’m trying to figure out how to automatically bind a simple key value pair of json to a form collection. I don’t want to create an object to bind the json with because I need to be more flexibility to dynamically create them based on some other information.
Thoughts as how I can do this?
Anything is greatly appreciated,
Matthew
It seems you will need to create a custom binder, that will automatically bind the data to the IDictionary.
The Binder
You should register the binder in Global for IDictionary<> type. There are also other ways to register the binders.
And finally, you should be able to use IDictionary<>. This will be bound to all the properties you will pass from ajax