How to build an ASP. Mvc4&jquery&ajax&json sample

Source: Internet
Author: User
Tags button type

Background:

A small example will be built in the blog to demonstrate how to use jquery Ajax in an ASP. NET MVC4 project.

View the JSON section directly

Steps:

1, add the controller (HomeController) and action Method (index), and add a view (index.cshtml) for the Index action method, the HTML in the view is as follows:

Enter your name:<input type="text"Id="txtname"/><br/>Enter your age:<input type="text"Id="txtage"/&GT;&LT;BR/><button type="Button"Id="BTN1"> Submit </button><button type="Button"Id="btn2"> Emptying </button><p id="Display"></p>

The view contains two text boxes, respectively, to enter a name and age, including a button to submit information and empty the contents of the text box, together with a paragraph to display the data information returned by Ajax.

2, add another Action Party (addusers) in the home controller to receive and process the data passed by the view, and return the execution result to the view, the code is as follows:

1          Publicactionresult addusers ()2         {3             varmy =NewMyModel ();4             stringresult =string. Empty;5             if(Request.isajaxrequest ())6             {7                  This. Updatemodel (my);8                 stringName =My. Name;9                 intAge =My. Age;Ten                 if(Age < -) result = name+"article is so rotten."; One                 Elseresult = name+", remember to write a rotten"; A             } -             returnContent (result); -}

As shown in the code: Returns a string directly with content.

or return a contentresult () object, similar to the code above (so collapsed), the code is as follows:

1          Publicactionresult dowithusers ()2         {3             varActionResult =default(Contentresult);4             varmy =NewMyModel ();5             Try6             {7                  This. Updatemodel (my);8                 stringName =My. Name;9                 intAge =My. Age;Ten                 stringtemp =""; One                 if(Age < -) temp ="article is so rotten."; A                 Elsetemp =", remember to write a rotten"; -ActionResult =NewContentresult () -                 { theContent = name +Temp -                 };  -             } -             Catch(Exception ex) +             { -                 return NULL; +             } A             returnActionResult; at}
View Code

3. Modify the Jquery&ajax code:

1 $ (document). Ready (function () {2$("#btn1"). Click (function () {3             vardata ="";4             varName = $ ("#txtName"). Val ();5             varAge = $ ("#txtAge"). Val ();6Data + ="&name="+encodeURI (name);7Data + ="&age="+encodeURI (age);8 $.ajax ({9                 Async:true,TenCachefalse, OneTimeout -* -* +, A Data:data, -Type"GET", -DataType"JSON", theUrl:"/ajax/addusers", - success:function (Result) -                 { -$("#display"). Text (result); +                 }, - error:function (Result) { +$("#display"). HTML ("Error"); A                 }, at             }) -});

4, Operation effect

Above, the simplest example of the ASP. NET Mvc4&jquery&ajax is complete.

Send an action-processed result in JSON:

In more cases, it is not just about returning a string, but instead returning the result in JSON.

5, modify the action as follows:

1          Publicactionresult dowithusers ()2         {3             varmy =NewMyModel ();4             Try5             {6                  This. Updatemodel (my);7                 stringName =My. Name;8                 intAge =My. Age;9                 stringtemp ="";Ten                 if(Age < -) temp ="article is so rotten."; One                 Elsetemp =", remember to write a rotten"; AJavaScriptSerializer JSS =NewJavaScriptSerializer (); -                 returnJson (JSS. Serialize (New{name = name, Message =temp}), jsonrequestbehavior.allowget); -             } the             Catch(Exception ex) -             { -                 return NULL; -             } +}

Description: The JSON method returns a Jsonresult, while Jsonresult is also inherited from ActionResult.

6, modify the Ajax section, the code is as follows:

1                 success:function (Result)2                {3                     result = Json.parse (result); 4                     $ ("#display"). Text (result. Name + result. Message); 5                 },

Run in the same effect.
Above, the simplest example of the ASP. NET Mvc4&jquery&ajax&json is complete.

How to build an ASP. Mvc4&jquery&ajax&json sample

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.