a blog for those who code

Thursday 13 April 2017

Partial Page Updates using Unobtrusive Ajax in ASP.NET MVC

In this post we will be discussing about performing partial page updates using unobtrusive Ajax in ASP.NET MVC. Certain times we only wants certain section of the page to load without loading the full html page. To do this we will be using an unobtrusive Ajax in ASP.NET MVC which will allow us to update only the section of the page.

Lets say we have a contact page and then when user clicks on Submit button we want only that section should be updated with certain message and not the whole page should load again. To use the Unobtrusive Ajax for doing partial page updates we need to install a Nuget Package called Microsoft.jQuery.Unobtrusive.Ajax which is a jQuery plugin that unobtrusively sets up jQuery Ajax.


After installing it we need to write a div which has the contents to use Ajax Unobtrusively as shown below :

<div id="myContactForm">
    @using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "post", InsertionMode = InsertionMode.Replace, UpdateTargetId = "myContactForm" }))
    {
        <label>Contact Us</label>
        <textarea name="contact" class="input-group"></textarea>
        <button class="btn btn-primary" id="contact-btn">Submit</button>
    }
</div>
@section Scripts {
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
}

We are using the Insertion Mode as Replace instead we can also use ReplaceWith. The difference between Replace and Replace with is that replace will replace the contents of the myContactForm div keeping the div whereas replacewith will replace the entire div.

Next thing is to add a Partial View and on call of the Contact Form return the PartialView and not the whole view as shown below :

[HttpPost]
public ActionResult Contact(string message)
{
  ViewBag.Message = "Thanks for the Message, we will get back to you";
  return PartialView("_ContactMessage");
}

Now when you write some message and click on Submit it will reload just the section instead of whole page.

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment