c# - Bind simple json to MVC Form Collection -
i'm trying bind simple json object (just key value pairs) mvc form collection or of 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 on 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 figure out how automatically bind simple key value pair of json form collection. don't want create object bind json because need more flexibility dynamically create them based on other information.
thoughts how can this?
anything appreciated,
matthew
it seems need create custom binder, automatically bind data idictionary.
the binder
public class dictionarymodelbinder : defaultmodelbinder { public override object bindmodel(controllercontext controllercontext, modelbindingcontext bindingcontext) { //get posted json var request = controllercontext.httpcontext.request; var jsonstringdata = new streamreader(request.inputstream).readtoend(); //use newtonsoft.json deserialise json idictionary return jsonconvert.deserializeobject<idictionary<string,string>>(jsonstringdata); } } you should register binder in global idictionary<> type. there other ways register binders.
protected void application_start() { ...other logic modelbinders.binders.add(typeof(idictionary<string, string>), new dictionarymodelbinder()); ...other logic } and finally, should able use idictionary<>. bound properties pass ajax
public actionresult youraction(idictionary<string, string> values) { ... logic here }
Comments
Post a Comment