Introduction
This article explains how we can use AJAX in ASP.NET MVC. Here, I tried to explain how to use Ajax.Beginform() for updating a part of page asynchronously. In this article, We will see how to load a Partial View onchange of selected Country dropdownlist (populated with some Country name).
Requirement
Visual studio 2012 or above.
Used keyword details
Ajax.Beginform: is a method
Partial View: Partial View in MVC Design pattern.
Creating MVC Project
Create new MVC Project in Visual studio as:
Creating Controller
Create a controller named 'AjaxDemo' as:
Controller code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Ajax.Controllers
{
public class AjaxDemoController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult GetCountryInformation(FormCollection collection)
{
ViewData["Country"] = collection.GetValue("ddlcountry").AttemptedValue;
return PartialView();
}
}
}
Creating Views:
Index.cshtml:
@{
Layout =null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
</head>
<body>
<div>
@using (Ajax.BeginForm("GetCountryInformation", "AjaxDemo",null, new AjaxOptions { UpdateTargetId = "dvCountryDetails", HttpMethod = "Post" }, new { id="AjaxFormCountry"}))
{
<label>Select Country</label>
<select name="ddlcountry" id="ddlcountry" onchange="CountyChange();">
<option value="-">Select</option>
<option value="India">India</option>
<option value="US">US</option>
</select>
<h4>Country Details</h4>
<div id="dvCountryDetails">
</div>
}
</div>
<script>
function CountyChange() {
$("#AjaxFormCountry").submit();
}
</script>
</body>
</html>
GetCountryInformation.cshtml:
@ViewData["Country"] is selected.
Enabling unobtrusive JavaScript
Also, we need to enable unobtrusive JavaScript by adding the "UnobtrusiveJavaScriptEnabled" key in the <configuration> section in the Web.config file as:
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
RouteConfig.cs:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name:"AjaxPartial",
url:"Ajax/GetCountryInformation",
defaults: new { controller = "AjaxDemo", action = "GetCountryInformation" }
);
routes.MapRoute(
name:"Default",
url:"{controller}/{action}/{id}",
defaults: new { controller = "AjaxDemo", action = "Index", id = UrlParameter.Optional }
);
}
Conclusion
I hope this will help you for develping web application with latest version of asynchronously call (Ajax call) in MVC.
Jak
13-Dec-2015 at 06:57