Beruflich Dokumente
Kultur Dokumente
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.
Description
Url
HttpMethod
Confirm
OnBegin
OnComplete
OnSuccess
OnFailure
LoadingElementId
LoadingElementDuration
UpdateTargetId
InsertionMode
Now that you have some basic understanding of Ajax helper, let's create a web application that
illustrates what we discussed so far.
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:
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.
4.
5.
6.
7.
8.
9.
select c;
10.
return View(data.SingleOrDefault());
11.
12.
13.
[HttpPost]
14.
15.
16.
17.
18.
select c;
19.
20.
cust.CompanyName = obj.CompanyName;
21.
db.SaveChanges();
22.
23.
24.
25.
[HttpPost]
26.
27.
28.
29.
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 />
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.
6. }
7. function OnSuccess() {
8.
9. }
10. function OnFailure() {
11.
12. }
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.
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
Downloads
AjaxHelperMVC-Code.zip
Comments