How to use AJAX In ASP.NET MVC

This post shows you how to Implement AJAX in ASP.NET MVC. Ajax is the ability to read data and communicate information asynchronously.

It's a fundamental for modern web applications.

You can create a new ASP.NET MVC project, then open _Layout file in the View\Shared folder and modify your html code as shown below.

<ul class="nav navbar-nav">
    <li>@Ajax.ActionLink("Home", "Index", "Home", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "ContentPanel" })</li>
    <li>@Ajax.ActionLink("About", "About", "Home", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "ContentPanel" })</li>
    <li>@Ajax.ActionLink("Contact", "Contact", "Home", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "ContentPanel" })</li>
</ul>

Remember add id = "ContentPanel" to div tag, it will be pasted content of your Partial View when calling an ajax action link. As you can see UpdateTargetId = "ContentPanel" and InsertionMode = InsertionMode.Replace in Ajax.ActionLink

<div id = "ContentPanel" class="container body-content">
    @RenderBody()
    <hr />
    <footer>
        <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
    </footer>
</div>

Open HomeController, then modify the return code to PartialView instead of View

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return PartialView();
    }

    public ActionResult About()
    {
        ViewBag.Message = "Your application description page.";
        return PartialView();
    }

    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";
        return PartialView();
    }
}

Open About view, then modify as below

@{
    ViewBag.Title = "About";
    Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml";
}

If ajax calls you should set the layout to null and vice versa. You can do the same as for Contact and Index actions.

Remember install jquery.unobtrusive-ajax from Nuget Package Manager, then set UnobtrusiveJavaScriptEnabled is true in the web.config. Let's play demo you can see how to it work.

<appSettings>
    <add key="webpagesersion" 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>