When using MVC, it is sometimes necessary to pass an array as a parameter value when sending a POST request to the server side
Let's take a look at the action below using the example
[HttpPost] Public ActionResult Test (list<string> model) { return Json (null, Jsonrequestbehavior.allowget);}
Type one, construct the form element, and then call the Serialize () method to get the constructor argument string
@{Layout = null;}<!DOCTYPE HTML><HTML><Head> <Metaname= "Viewport"content= "Width=device-width" /> <title>Test</title></Head><Body> <Div> <inputtype= "button"ID= "Btnajax"value= "Send Request" /> </Div> <Scriptsrc= "~/scripts/jquery-1.10.2.min.js"></Script> <Scripttype= "Text/javascript"> vartmp= '<input type= "hidden" name= "model" value= "1"/><input type= "hidden" name= "model" value= "2"/>'; $(function () { $("#btnAjax"). Click (function() {$.ajax ({URL:'@Url. Action ("Test")', type:'POST', Data: $ (TMP). Serialize (), Success:function(JSON) {console.log (JSON); } }); }); }); </Script></Body></HTML>
Debug mode monitoring parameters, when the button is clicked, the parameters monitored are as follows
Method Two: Use a JavaScript object as a parameter value, the parameter name is the parameter name corresponding to the action method, the parameter value is a JavaScript array
@{Layout = null;}<!DOCTYPE HTML><HTML><Head> <Metaname= "Viewport"content= "Width=device-width" /> <title>Test</title></Head><Body> <Div> <inputtype= "button"ID= "Btnajax"value= "Send Request" /> </Div> <Scriptsrc= "~/scripts/jquery-1.10.2.min.js"></Script> <Scripttype= "Text/javascript"> //var tmp = ' <input type= ' hidden "name=" model "value=" 1 "/><input type=" hidden "name=" model "value=" 2 "/> '; varArray= ["ABC","123"]; $(function () { $("#btnAjax"). Click (function() {$.ajax ({URL:'@Url. Action ("Test")', type:'POST', data: {Model:array}, Success: function(JSON) {console.log (JSON); } }); }); }); </Script></Body></HTML>
Method three, using JSON as the parameter request, at this time Ajax needs to declare Content-type as Application/json
@{Layout = null;}<!DOCTYPE HTML><HTML><Head> <Metaname= "Viewport"content= "Width=device-width" /> <title>Test</title></Head><Body> <Div> <inputtype= "button"ID= "Btnajax"value= "Send Request" /> </Div> <Scriptsrc= "~/scripts/jquery-1.10.2.min.js"></Script> <Scripttype= "Text/javascript"> //var tmp = ' <input type= ' hidden "name=" model "value=" 1 "/><input type=" hidden "name=" model "value=" 2 "/> '; //var array = ["abc", "123"]; $(function () { $("#btnAjax"). Click (function() {$.ajax ({URL:'@Url. Action ("Test")', type:'POST', contentType: 'application/json;charset=utf-8' , data: json.stringify({model:["Hello","Welcome"]}), success:function(JSON) {console.log (JSON); } }); }); }); </Script></Body></HTML>
The above example uses ASP. NET MVC 5
Jquery Ajax passes array parameter values to the service side