Today, in contact with the mvc4.0 project, the view needs to get JSON data from control. The process is documented as follows:
In the ActionResult returned by MVC, we are provided with an jsonresult (inheriting to ActionResult) object, which we can use directly to return the JSON object to the view processing
The custom model instance is passed to the JSON method, which automatically builds the JSON object and returns the view based on the properties of our model, after traversing the properties. The JSON data can then be processed using JQ on the front end.
The code in control:
PublicJsonresult Search () {stringName = request.querystring["name"]??""; varLists =NewList<maticsoft.model.newslist> ();//Type CollectionNEWSLISTBLL BLL =NewNEWSLISTBLL (); Lists= BLL. Getmodellist ("name like '%"+name+"% '"); Jsonresult JSON=NewJsonresult (); Json. Data=lists; returnJson (Json,jsonrequestbehavior.allowget); //Jsonrequestbehavior.allowget must be turned on or it will be an error . }
The code in view:
<script type= "Text/javascript" > $(function () { $("#cx"). Click (function () { varName = $ ("#txtName"). Val (); $.getjson ("Search", {name:name},function(data) {varmsg = "<tr><td> User name </td><td> page address </td><td> picture name </td></tr>"; for(vari = 0, length = data. Data.length; i < length; i++) {msg+ = "<tr><td>" +data. Data[i].name+ "</td><td>" +data. data[i].url+ "</td><td>" +data. data[i].img+ "</td></tr>"; } $("#userlist"). HTML (msg); }); }); });</script> <table style= "width:100%;" id= "UserList" ></table>