Let’s talk today a little bit about very useful and easy to use in MVC 3 jQuery library called jQuery.Ajax.Unobtrusive. With a MVC 1 and 2 Microsoft provide library to work with AJAX requests. Already then was created Ajax helper to render form and link with unobtrusive parameters for AJAX requests. But these parameters were handled only by MicrosoftMvcAjax JavaScript library. The problem is that this library is what a lot of users doesn’t want it to use. Instead, they prefer to use jQuery – “write less, do more”. With MVC 3 situation become better. Microsoft released jQuery.Ajax.Unotrusive JavaScript library. I will show you how easy we can make AJAX form (or action link) with Ajax helper and the JavaScript library.

First of all check if unobtrusive JavaScript is enabled in application settings:

<!-- Web.config -->
	<appSettings>
		<add key="UnobtrusiveJavaScriptEnabled" value="true" />
		…
	</appSettings>

Second, include jQuery.Ajax.unobrusive.js into the view. The library goes with default MVC 3 project (in the Scripts folder) or you can download it from NuGet. It is also available from Microsoft CDN network:

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.unobtrusive-ajax.min.js"></script>

And that’s it! Yes, you can start using Ajax helper. Example:
Partial View (Modules/Address.cshtml):

@model Address
<h3>Address</h3>
@using (Ajax.BeginForm("Address", new AjaxOptions() { UpdateTargetId = "address", OnSuccess="AddressSaved", InsertionMode = InsertionMode.Replace, HttpMethod = "Post" })) {
	<fieldset>
	  <legend>Address and contact info</legend>
	  @Html.LabelFor(model => model.Street)
	  @Html.EditorFor(model => model.Street)
	  <input type="submit" value="Save" />
	</fieldset>
	}

Parent view:

@model AccountModel
<h2>Account</h2>
	<div id="address">
	  @{ Html.RenderPartial("Modules/Address", Model.Address); }
	</div>

Controller:

[HttpPost]
public ActionResult Address(Address address) {
	if (ModelState.IsValid) {
	  //Save object
	}
	ModelState.Clear();
	}
	if (Request.IsAjaxRequest())
	  return PartialView("Modules/Address", address);
	else
	  return RedirectToAction("Index");
	}

JavaScript:

function AddressSaved() {
	alert(‘Address saved!’);
};

Explanation:

using (Ajax.BeginForm("Address", new AjaxOptions() { UpdateTargetId = "address", OnSuccess="AddressSaved", InsertionMode = InsertionMode.Replace, HttpMethod = "Post" }))

will render form with action linked to “Address” action in controller. AjaxOptions:  UpdateTargetId = "address" – id of the DOM element that will be updated after AJAX call. OnSuccess="AddressSaved" – AddressSaved – name of the JavaScript function that will be executed on success AJAX response. InsertionMode = InsertionMode.Replace – indicates that content of specified DOM element will be replaced with a response content. HttpMethod = "Post" – Request type.

In this example: when user hits the submit button, collected form data will be submitted with AJAX request to Address action in the controller and after successful response content if <div id=”address”></div> will be replaced with a new content sent from controller:  PartialView("Modules/Address", address).

All possible AjaxOptions:

public class AjaxOptions {
	public string Confirm { get; set; }
	public string HttpMethod { get; set; }
	public InsertionMode InsertionMode { get; set; }
	public int LoadingElementDuration { get; set; }
	public string LoadingElementId { get; set; }
	public string OnBegin { get; set; }
	public string OnComplete { get; set; }
	public string OnFailure { get; set; }
	public string OnSuccess { get; set; }
	public string UpdateTargetId { get; set;}
	public string Url { get; set; }
}

So to show loading image/panel on AJAX call use OnBegin JavaScript function to show loading image and to hide it – use function assigned to OnSuccess.

BTW, pagination on this website implemented using this approach as well but instead of Ajax.Form, Ajax.ActionLink is used.
Questions? Feel free to ask in comments or by email. Happy codding!

Source:

Comments

hofnarwillie
10 June 2012 | 07:15 +01:00

Thank you. Very helpful!

anton putov
24 July 2012 | 00:28 +03:00

Thanks for your post.I saw a lot of examples but no one explain this moment :@RenderPartialView... . So thats why I couldnt upgrade my <div> block.Thank you very much!!! 

Antonio Espinosa
02 April 2014 | 10:42 -06:00

thank you mate! that little piece of info helped me a lot, guys don't try to put the <script src="~/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script> in a layout just put it in the view the view also needs to have a html tags and head and a body that was my problem i hope this helps , otherwise you will be redirected to the partial view ;)

adityakumar
25 January 2016 | 19:00 +05:30
Nice Articles .

Join the discussion

Captcha