Model:
namespace mvcapplication1.models{ publicclass Team { public Stringgetset;} Public string Get Set ; } }}
Loading partial views asynchronously via jquery
In the home/index.cshtml view:
@{Viewbag.title="Index"; Layout="~/views/shared/_layout.cshtml";}"#"Id="a"> Asynchronous </a> <br/></div><div id= via jquery"result"> </div>@section scripts{<script type="Text/javascript">$ (function () {$ ('#a'). Click (function () {$.ajax ({URL:'@Url. Action ("Index", "Home")', data: {pre:'B'}, type:'POST', Success:function (data) {$ ('#result'). Empty (). append (data); } }); return false; }); }); </script>}
In the HomeController controller:
usingSystem.Collections.Generic;usingSystem.Linq;usingSYSTEM.WEB.MVC;usingMvcapplication1.models;namespacemvcapplication1.controllers{ Public classHomecontroller:controller { PublicActionResult Index () {returnView (); } [HttpPost] PublicActionResult Index (stringpre) { varresult = Getallteams (). Where (t = = T.preletter = =pre). ToList (); Viewbag.msg="get here asynchronously via jquery ~ ~"; returnPartialview ("Teamy", result); } PrivateList<team>Getallteams () {return NewList<team>() { NewTeam () {Name ="Brazil Team", Preletter ="B"}, NewTeam () {Name ="Croatian Team", Preletter ="K"}, NewTeam () {Name ="Paraguay", Preletter ="B"}, NewTeam () {Name ="South Korea", Preletter ="K"} }; } }}
Partial view teamy.cshtml:
@model ienumerable<mvcapplication1.models.team> @{ varstring. Empty; foreach (var in Model) { ","; }} @ViewBag. msg.tostring ()<br/>@result. Substring (01)
Asynchronously loading partial views via MVC Ajax Helper
The home/index.cshtml view requires reference to the Jquery.unobtrusive-ajax.js file, and the strongly typed partial view content returned from the controller is rendered to the Updatetargetid specified div.
@{Viewbag.title="Index"; Layout="~/views/shared/_layout.cshtml";}@Ajax. ActionLink ("through MVC Ajax Helper","Load","Home",New{pre ="K"},NewAjaxoptions () {Updatetargetid ="RESULT1"})</div><div id="RESULT1"></div>
In the HomeController controller:
usingSystem.Collections.Generic;usingSystem.Linq;usingSYSTEM.WEB.MVC;usingMvcapplication1.models;namespacemvcapplication1.controllers{ Public classHomecontroller:controller { PublicActionResult Index () {returnView (); } PublicActionResult Load (stringpre) { varresult = Getallteams (). Where (t = = T.preletter = =pre). ToList (); Viewbag.msg="get here through MVC Ajax Helper ~ ~"; returnPartialview ("Teamy", result); } PrivateList<team>Getallteams () {return NewList<team>() { NewTeam () {Name ="Brazil Team", Preletter ="B"}, NewTeam () {Name ="Croatian Team", Preletter ="K"}, NewTeam () {Name ="Paraguay", Preletter ="B"}, NewTeam () {Name ="South Korea", Preletter ="K"} }; } }}
The partial view is the same as the previous one.
How page refreshes load partial view methods include:
Html.renderpartial ()
Html.renderaction ()
MVC Ajax Helper or jquery asynchronously loads a partial view