Sie sind auf Seite 1von 9

Working with Ajax Helper in ASP.

NET MVC
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.

Rapid Response to Feedback Continuous Delivery in a Mobile World


Download Now
Notice the difference between these two features. The former feature allows you to submit an
entire <form> to an action method whereas the later feature simply invokes a specified action
method. To submit a form using Ajax helper you use BeginForm() helper method and to invoke
an action method you use ActionLink() helper method.
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.
1. public class HomeController : Controller
2. {
3.

NorthwindEntities db = new NorthwindEntities();

4.
5.

public ActionResult Index()

6.

7.

var data = from c in db.Customers

8.

where c.CustomerID == "ALFKI"

9.

select c;

10.

return View(data.SingleOrDefault());

11.

12.
13.

[HttpPost]

14.

public string ProcessForm(Customer obj)

15.

16.

var data = from c in db.Customers

17.

where c.CustomerID == obj.CustomerID

18.

select c;

19.

Customer cust = data.SingleOrDefault();

20.

cust.CompanyName = obj.CompanyName;

21.

db.SaveChanges();

22.

return "<h2>Customer updated successfully!</h2>";

23.

24.
25.

[HttpPost]

26.

public string ProcessLink()

27.

28.
29.

return "<h2>This is a response from action method!</h2>";


}

30. }

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.
1. <body>
2. <%
3. AjaxOptions options = new AjaxOptions();
4. options.HttpMethod = "POST";
5. options.Confirm = "Do you wish to submit this form?";
6. options.OnBegin = "OnBegin";
7. options.OnComplete = "OnComplete";
8. options.OnFailure = "OnFailure";
9. options.OnSuccess = "OnSuccess";
10. options.LoadingElementId = "divProgress";
11. options.LoadingElementDuration = 1000;
12. options.UpdateTargetId = "divResponse";
13. options.InsertionMode = InsertionMode.InsertAfter;
14. %>
15.
16. <% using(Ajax.BeginForm("ProcessForm","Home",options)){ %>
17. <%= Html.LabelFor(c=>c.CustomerID) %>
18. <br />
19. <%= Html.TextBoxFor(c=>c.CustomerID,new {@readonly="readonly"}) %>
20. <br />
21. <%= Html.LabelFor(c=>c.CompanyName) %>
22. <br />

23. <%= Html.TextBoxFor(c=>c.CompanyName) %>


24. <br />
25. <input type="submit" value="Submit" />
26. <br />
27. <br />
28. <%= Ajax.ActionLink("Click here to invoke ProcessLink
action.","ProcessLink",options) %>
29. <%}%>
30.
31. <br />
32. <br />
33. <div id="divProgress">
34. <img src='<%= Url.Content("~/images/ProgressCircle.gif") %>' />
35. </div>
36. <div id="divResponse"></div>
37. <div id="divMsg"></div>
38. </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.
1. <script src='<%= Url.Content("~/Scripts/jquery-1.7.1.min.js")
%>'></script>
2. <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.
1.
2.

function OnBegin() {
$("#divMsg").append("<h3>Beginning Ajax request.</h3>");

3. }
4. function OnComplete() {
5.

$("#divMsg").append("<h3>Completing Ajax request.</h3>");

6. }
7. function OnSuccess() {
8.

$("#divMsg").append("<h3>Ajax request successful.</h3>");

9. }
10. function OnFailure() {
11.
12. }

$("#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.
1. $(document).ready(function () {
2.

$("#divProgress").css("display","none");

3. });

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.

Related Articles

Using SimpleMembership in ASP.NET MVC 4

Validating Data Using Data Annotation Attributes in ASP.NET MVC

Using Cross Origin Resource Sharing (CORS) in ASP.NET Web API

Sending Notifications using ASP.NET SignalR

Downloads

AjaxHelperMVC-Code.zip

Comments

Das könnte Ihnen auch gefallen