One
Prepare the background test data, the process is slightly
Second, the client processing
@{Viewbag.title="Index";}"width:600px;"> <div style="Background-color:lightgray"> "Btnajax"Name="Btnajax"Type="Button"Value="Get Meals"/> <div id="Meals"style="Background-color:lightskyblue"></div> <div id="Jsonresult"style="Background-color:lightsalmon"></div></div><div style="Background-color:lightpink;display:none;"Id="Updatemealdiv"> <table> <tr> <th>Name</th> <th>Comments</th> <th>Picture</th> </tr> <tr> <td><input type="text"Id="txtname"Name="txtname"/></td> <td><input type="text"Id="txtcomment"Name="txtcomment"/></td> </tr> </table> <input type="Button"Value="Update Meal"Id="Btnupdatemeal"Name="Btnupdatemeal"></div><script type="Text/javascript"> $("#btnAjax"). Click (function () {$.ajax ({URL:'/ajaxdemo/getmeal', ContentType:'application/html; Charset=utf-8', type:'Get', datatype:'HTML'}). Success (function (data) {$ ("#meals"). HTML (data); $("#updateMealDiv"). Show (). AppendTo ($ ("#meals")); }). Error (Function (XHR, status, Errorthrown) {alert (errorthrown); }) }); $("#btnUpdateMeal"). Click (function () {varNameval = $ ("#txtName"). Val (); varCommentval = $ ("#txtComment"). Val (); $.ajax ({URL:'/ajaxdemo/getjsonstring', Data:JSON.stringify ({name:nameval, comment:commentval}), type:'Post', ContentType:"Application/json; Charset=utf-8"}). Success (function (data) {varResultStr ="<ul><li>"+ Data.newname +"</li><li>"+ Data.newcomment +"</li></ul>"; $("#jsonResult"). HTML (RESULTSTR); }). Error (Function (XHR, status, errormsg) {alert (errormsg); }) });</script>
View Code
Third, Controller processing
Using Json.stringify () to process JSON strings
Public classAjaxdemocontroller:controller {PrivateDb DbContext =NewDb (); // //GET:/ajaxdemo/ PublicActionResult Index () {returnView (); } PublicActionResult getmeal () {meal[] meals= DbContext.Meals.Where (m = m.id <=5). ToArray (); returnPartialview ("getmeals", meals); } PublicActionResult getjsonstring (stringNamestringcomment) { returnJson (New{newName = name +"Luxuan", NewComment = comment +"lllll" }); } PublicActionResult Updatemeal (stringMname,stringcomment) {IList<Meal> meallist =dbContext.Meals.ToList (); Meal Updatedmeal= Meallist.where (m = M.name = =mname). Single (); Updatedmeal.name=Mname; Updatedmeal.comments=comment; Dbcontext.savechanges (); Meallist= Meallist.where (m = m.id <=5). ToArray (); returnPartialview ("getmeals", meallist); } }
View Code
Iv. Results of operation
Ajax retrieve JSON data and Html data from MVC Controllers in ASP. NET MVC