The purpose of this example is to illustrate how one of my controllers receives the JSON object or array information from the AJAX submission (POST), and feels there should be a better way to welcome the valuable advice.
Json.stringify (jsonobj) does not support IE8 the following browsers
The front page code is as follows:
1 <Scripttype= "Text/javascript"src= "~/scripts/jquery-1.11.3.js"></Script>2 <formID= "FM">3 <Div>4 <inputID= "BTN"type= "button"value= "Submit"onclick= "Savetest ()" />5 </Div>6 </form>7 <Script>8 functionsavetest () {9 varJsonobj= [];Ten Jsonobj.push ({"ID":1,"name":"123"}); One Jsonobj.push ({"ID":2,"name":"234"}); A Jsonobj.push ({"ID": 3, "name": "345" }); - $.ajax ({ - URL:"/test/save", the Type:"Post", - DataType:"JSON", - Async:false, - data:JSON.stringify (jsonobj), + Success:function(data) { - + }, A Error:function(XMLHttpRequest, Textstatus, Errorthrown) { at alert (xmlhttprequest.status); - alert (xmlhttprequest.readystate); - alert (textstatus); - } - }); - } in </Script>
The Controller->action code is as follows (you need to reference the System.IO and System.Web.Script.Serialization namespaces):
1 [HttpPost]2 Publicactionresult Save ()3 {4 varSR =NewStreamReader (request.inputstream);5 varstream =Sr. ReadToEnd ();6JavaScriptSerializer js =NewJavaScriptSerializer ();7 varList = js. Deserialize<list<models.selectlist>>(stream);8 if(list. Any ())9 {Ten foreach(varIteminchlist) One { A - } - } the returnView (); -}
SelectList object class (class can be added here [Serializable] or no, because there is no direct transfer or storage of SelectList objects, so I do not add)
1 Public Partial classSelectList2 {3 Public intID {Get;Set; }4 5 Public stringName {Get;Set; }6 7 Public stringText {Get;Set; }8}
The general idea is to convert a JSON object or array into a string, which is passed to the server by the front end, request is received, and then deserialized into the entity object using JSON. Tried the action to add a string argument directly, but after entering the action, you cannot receive a JSON string that passes over. Of course, you can also save the JSON string directly in the hidden domain, and the form is submitted to the server for access.
The ASP. NET MVC controller receives the JSON object or array data sent by the Ajax post method