Introduction
Ajax driven web applications are quite common these days. While you can use libraries such as jQuery to make Ajax calls to ASP.NET MVC action methods there is an inbuilt way to Ajax enable your forms - Ajax helper. Using Ajax helper you can submit your HTML form using Ajax so that instead of refreshing the entire web page only a part of it can be refreshed. Additionally, you can also render action links that allow you to invoke action methods using Ajax. This article examines these two techniques provided by the Ajax helper.
Overview of Ajax Helper
Ajax helper of ASP.NET MVC essentially provides Ajax functionality to your web applications. Two core features of Ajax helper are as follows:
- You can submit an entire form using Ajax.
- You can invoke an action method using Ajax.
Various configuration options for AJAX Helpers
The AjaxOptions class defines properties that allow you to specify callbacks for different stages in the AJAX request life cycle. There are following properties provided by AjaxOptions class for AJAX helpers:
Property
Description
Url
Specify the URL that will be requested from the server.
Confirm
Specify a message that will be displayed in a confirm dialog to the end user. When user clicks on OK button in the confirmation dialog, the Ajax call performs.
OnBegin
Specify a JavaScript function name which is called at the beginning of the Ajax request.
OnComplete
Specify a JavaScript function name which is called at the end of the Ajax request.
OnSuccess
Specify a JavaScript function name which is called when the Ajax request is successful.
OnFailure
Specify a JavaScript function name which is called if the Ajax request fails.
LoadingElementId
Specify progress message container’s Id to display a progress message or animation to the end user while an Ajax request is being made.
LoadingElementDuration
Specify a time duration in milliseconds that controls the duration of the progress message or animation.
UpdateTargetId
Specify the target container’s Id that will be populated with the HTML returned by the action method.
InsertionMode
Specify the way of populating the target container. The possible values are InsertAfter, InsertBefore and Replace (which is the default).
What is Cross Domain AJAX?
By default, web browsers allows AJAX calls only to your web application’s site of origin i.e. site hosted server. This restriction help us to prevent various security issues like cross site scripting (XSS) attacks. But, sometimes you need to interact with externally hosted API(s) like Twitter or Google. Hence to interact with these external API(s) or services your web application must support JSONP requests or Cross-Origin Resource Sharing (CORS). By default, ASP.NET MVC does not support JSONP or Cross-Origin Resource Sharing. For this you need to do a little bit of coding and configuration
The Ajax helper allows you to configure several aspects of the Ajax request such as success callback and failure callback. These configuration options are available as the properties of AjaxOptions class. The following table lists these properties for your quick reference:
Property | Description |
Url | The Url property indicates a URL to which the form is to be submitted. You can also specify a controller and action method in the BeginForm() method instead of setting the URL property. |
HttpMethod | The HttpMethod property indicates the HTTP method (GET or POST) to be used while making an Ajax request. |
Confirm | The Confirm property is used to specify a message that will be displayed in a confirm dialog to the end user. If user clicks OK on the confirmation dialog the Ajax call is made. |
OnBegin | The OnBegin property specifies a name of JavaScript function that is called at the beginning of the Ajax request. |
OnComplete | The OnComplete property specifies a name of JavaScript function that is called at the end of the Ajax request. |
OnSuccess | The OnSuccess property specifies a name of JavaScript function that is called when the Ajax request is successful. |
OnFailure | The OnFailure property specifies a name of JavaScript function that is called if the Ajax request fails. |
LoadingElementId | While an Ajax request is being made you can display a progress message or animation to the end user. The LoadingElementId indicates an ID of a DOM element that is serving this purpose. Note that the Ajax helper will simply display and hide this element. Displaying some progress message of animation inside this element is your responsibility. |
LoadingElementDuration | The LoadingElementDuration property specifies a time duration in milliseconds that controls the duration of the progress message or animation. |
UpdateTargetId | The UpdateTargetId property specifies an ID of a DOM element that will be populated with the HTML returned by the action method. |
InsertionMode | The InsertionMode property governs how the HTML replacement should occur in a DOM element as specified by UpdateTargetId property. The possible values are InsertAfter, InsertBefore and Replace. |
Now that you have some basic understanding of Ajax helper, let's create a web application that illustrates what we discussed so far.
Creating a Form That Uses Ajax Helper Methods
Begin by creating a new ASP.NET MVC 4 project based on an empty project template. Right click on the models folder and add an Entity Framework data model for the Customers table of Northwind database. The Customer data model class is shown below:
Customer data model class
Although the Customer class contains many properties you will use just two for the sake of illustration - CustomerID and CompanyName.
Now add a new controller to the Controllers folder and name it HomeController. The following code shows the action methods that go inside the Home controller.
- public class HomeController : Controller
- {
- NorthwindEntities db = new NorthwindEntities();
- public ActionResult Index()
- {
- var data = from c in db.Customers
- where c.CustomerID == "ALFKI"
- select c;
- return View(data.SingleOrDefault());
- }
- [HttpPost]
- public string ProcessForm(Customer obj)
- {
- var data = from c in db.Customers
- where c.CustomerID == obj.CustomerID
- select c;
- Customer cust = data.SingleOrDefault();
- cust.CompanyName = obj.CompanyName;
- db.SaveChanges();
- return "<h2>Customer updated successfully!</h2>";
- }
- [HttpPost]
- public string ProcessLink()
- {
- return "<h2>This is a response from action method!</h2>";
- }
- }
As you can see the Home controller contains three action methods viz., Index(), ProcessForm() and ProcessLink(). The Index() action method simply selects a Customer with CustomerID of ALFKI and renders the Index view. Notice that the Customer object is passed as the data model for the Index view.
The ProcessForm() action method will be called by the Ajax helper from the Index view. The ProcessForm() action method accepts Customer object as the parameter. Inside, it simply changes the CompanyName property of an existing Customer object and saves the modifications by calling SaveChanges() method of the data context object. The ProcessForm() method returns an HTML string with a success message.
The ProcessLink() method is called by the Ajax ActionLink helper and simply returns some HTML markup with a message to the caller.
This completes the Home controller. Now, right click on the Index() action method and select the Add View menu option. Add Index view to the project and write the following markup in it.
- <body>
- <%
- AjaxOptions options = new AjaxOptions();
- options.HttpMethod = "POST";
- options.Confirm = "Do you wish to submit this form?";
- options.OnBegin = "OnBegin";
- options.OnComplete = "OnComplete";
- options.OnFailure = "OnFailure";
- options.OnSuccess = "OnSuccess";
- options.LoadingElementId = "divProgress";
- options.LoadingElementDuration = 1000;
- options.UpdateTargetId = "divResponse";
- options.InsertionMode = InsertionMode.InsertAfter;
- %>
- <% using(Ajax.BeginForm("ProcessForm","Home",options)){ %>
- <%= Html.LabelFor(c=>c.CustomerID) %>
- <br />
- <%= Html.TextBoxFor(c=>c.CustomerID,new {@readonly="readonly"}) %>
- <br />
- <%= Html.LabelFor(c=>c.CompanyName) %>
- <br />
- <%= Html.TextBoxFor(c=>c.CompanyName) %>
- <br />
- <input type="submit" value="Submit" />
- <br />
- <br />
- <%= Ajax.ActionLink("Click here to invoke ProcessLink action.","ProcessLink",options) %>
- <%}%>
- <br />
- <br />
- <div id="divProgress">
- <img src='<%= Url.Content("~/images/ProgressCircle.gif") %>' />
- </div>
- <div id="divResponse"></div>
- <div id="divMsg"></div>
- </body>
The Index view contains a code block that creates the AjaxOptions object. The HttpMethod property sets the HTTP method for the Ajax called to be POST. The Confirm property sets a confirmation message that is to be displayed to the end user. OnBegin, OnComplete, OnSuccess and OnFailure properties specify the respective JavaScript functions. You will write these functions shortly. The LoadingElementId property specifies a progress element to be divProgress. This <div> can be found in the HTML markup of the form towards the bottom of the page. Similarly, UpdateTargetId property specifies the target element to be divResponse. The InsertionMode mode is set to InsertAfter so that the return value from the action method is inserted after the existing content of the target element.
Then the view renders an Ajax form using the Ajax.BeginForm() helper method. The first two parameters of the BeginForm() are action method name and controller name respectively whereas the third parameter is an object of type AjaxOptions. The form fields are rendered using LabelFor() and TextBoxFor() helper methods. A submit button is used to submit the form.
Below the submit button is a hyperlink. The hyperlink is rendered using the Ajax.ActionLink() helper method. The first parameter of the ActionLink() method is the text to be displayed in the hyperlink, the second parameter is the action method that is to be called and the third parameter is the AjaxOptions object.
Below the form are three <div> elements. The divProgress element is used to display an animated progress image (ProgressCircle.gif in this case). The divResponse is used to display the response of the ProcessForm() action method. The divMsg is used by OnBegin, OnComplete, OnSuccess and OnFailure functions to display some message. Before you write these JavaScript functions add a script reference in the head section of the view as shown below.
- <script src='<%= Url.Content("~/Scripts/jquery-1.7.1.min.js") %>'></script>
- <script src='<%= Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js") %>'></script>
The first <script> tag adds a reference to the jQuery library whereas the second <script> block adds a reference to the jquery.unobtrusive-ajax library. These files are needed for the correct functioning of Ajax helpers and this example assumes that you have them in the Scripts folder of the web application.
Now add the four JavaScript functions mentioned earlier. The OnBegin, OnComplete, OnSuccess and OnFailure functions are shown below.
- function OnBegin() {
- $("#divMsg").append("<h3>Beginning Ajax request.</h3>");
- }
- function OnComplete() {
- $("#divMsg").append("<h3>Completing Ajax request.</h3>");
- }
- function OnSuccess() {
- $("#divMsg").append("<h3>Ajax request successful.</h3>");
- }
- function OnFailure() {
- $("#divMsg").append("<h3>Ajax request failed.</h3>");
- }
As you can see all these functions simply append a message to divMsg using append() method of jQuery.
One final thing you need to do is to hide the divProgress initially when the page loads. You can do so through a CSS class or through jQuery as shown below.
- $(document).ready(function () {
- $("#divProgress").css("display","none");
- });
The above code uses css() method of jQuery to set display CSS property to none.
That's it! You can now run the application and test if Ajax requests are being made correctly. The following figure shows a sample run of the application.
Sample run of the application
Notice how the progress animation is displayed when you click on the Submit button. Also, notice the messages displayed in the divResponse and divMsg.
Summary
ASP.NET MVC provides Ajax helpers that can be used to invoke action methods using Ajax. The Ajax.BeginForm() can be used to submit a form to an action method using Ajax whereas Ajax.ActionLink() can be used to render an anchor element that invokes an action method when clicked. The AjaxOptions class provides several properties that govern how the Ajax request is made. The Ajax.BeginForm() and Ajax.ActionLink() methods accept an object of type AjaxOptions in addition to action and controller name.
Article Source From:Msdn,
http://www.dotnet-tricks.com/,
Article Source From:Msdn,
http://www.dotnet-tricks.com/,
www.codeguru.com/.../working-with-ajax-helper-in-asp.net-mvc.htm
0 comments:
Post a Comment