Using JSON data in mvc4.0

Source: Internet
Author: User

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>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.