MVC Ajax Helper or jQuery asynchronously loads some views, mvcjquery
Model:
namespace MvcApplication1.Models{ public class Team { public string Preletter { get; set; } public string Name { get; set; } }}
Asynchronously load partial views using jQuery
In the Home/Index. cshtml View:
@ {ViewBag. Title = "Index"; Layout = "~ /Views/Shared/_ Layout. cshtml ";}
In the HomeController controller:
Using System. collections. generic; using System. linq; using System. web. mvc; using MvcApplication1.Models; namespace MvcApplication1.Controllers {public class HomeController: Controller {public ActionResult Index () {return View ();} [HttpPost] public ActionResult Index (string pre) {var result = GetAllTeams (). where (t => t. preletter = pre ). toList (); ViewBag. msg = "arrived here through jQuery Asynchronous Method ~~ "; Return PartialView (" TeamY ", result);} private List <Team> GetAllTeams () {return new List <Team> () {new Team () {Name = "Brazil", Preletter = "B"}, new Team () {Name = "Beijing", Preletter = "K"}, new Team () {Name = "Paraguay", Preletter = "B"}, new Team () {Name = "Korea", Preletter = "K "}};}}}
Part of the view TeamY. cshtml:
@model IEnumerable<MvcApplication1.Models.Team> @{ var result = string.Empty; foreach (var item in Model) { result += item.Name + ","; }}@ViewBag.msg.ToString()<br/>@result.Substring(0,result.Length - 1)
Asynchronously load partial views through MVC Ajax Helper
The jquery. unobtrusive-ajax.js file needs to be referenced in the Home/Index. cshtml view to render the contents of the strong part of the view returned by the Controller to the div specified by UpdateTargetId.
@ {ViewBag. Title = "Index"; Layout = "~ /Views/Shared/_ Layout. cshtml ";}< h2> Index
In the HomeController controller:
Using System. collections. generic; using System. linq; using System. web. mvc; using MvcApplication1.Models; namespace MvcApplication1.Controllers {public class HomeController: Controller {public ActionResult Index () {return View ();} public ActionResult Load (string pre) {var result = GetAllTeams (). where (t => t. preletter = pre ). toList (); ViewBag. msg = "here via MVC Ajax Helper ~~ "; Return PartialView (" TeamY ", result);} private List <Team> GetAllTeams () {return new List <Team> () {new Team () {Name = "Brazil", Preletter = "B"}, new Team () {Name = "Beijing", Preletter = "K"}, new Team () {Name = "Paraguay", Preletter = "B"}, new Team () {Name = "Korea", Preletter = "K "}};}}}
Some views are the same as the previous method.
Some view loading methods for page refreshing include:
Html. RenderPartial ()
Html. RenderAction ()