When ASP. NET MVC uses AJAX to request data, we typically return JSON or XML and parse the data for rendering, which can be cumbersome, request a partial action, return a partial view to render directly, and do not need to parse this step.
Here's an example:
Controller class:
Public classHomecontroller:controller {// //GET:/home/ PublicActionResult Index () {returnView (); } [HttpPost] PublicPartialviewresult Testaajaloginviewresult () {List<User> list=NewList<user>(); for(inti =0; I <Ten; i++) {list. ADD (NewUser {Id = I,name ="Name _"+i}); } returnPartialview (list); } }
User Class Model:
Public class User { publicintsetget;} Public string Set Get ; } }
Index.cshtml:
@{Viewbag.title="Index"; Layout="~/views/shared/_layout.cshtml";}<script src="/scripts/jquery-1.5.1.min.js"Type="Text/javascript"></script><script type="Text/javascript">$ (function () {$ ('#btnOK'). Click (function () {$.ajax ({type:"POST", URL:'/home/testaajaloginviewresult', data: {}, DataType:"HTML", Success:function (data) {$ ('#content'). append (data); }, Error:function () {alert ("processing failed!"); } }); }); });</script><input id="Btnok"Value="Click to load partial page data"/><div id="content"></div>
Testaajaloginviewresult.cshtml:
@model system.collections.generic.list<asp.netmvc3demo.controllers.user>@foreach (var inch Model) { <div> @item. Id</div> <div> @item. name</div> <br/>}
Note: This method is not recommended when loading big data if the amount of data that you request is very large and the loading speed slows down.
ASP. NET MVC uses the action of the AJAX Request controller (PARTIALVIEWRESULT) division to get a partial view (Partialview) of HTML for rendering