29.05.2015 Views

o_19mgorv9t13a3ko71fev19l81mqa.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Setting Ajax Options<br />

I can fine-tune the behavior of the Ajax requests by setting values for the properties of the AjaxOptions object that I pass to<br />

the Ajax.BeginForm helper method. In the following sections, I explain what each of these options does and why they can<br />

be useful.<br />

Ensuring Graceful Degradation<br />

When I set up the Ajax-enabled form in Listing 23-10, I passed in the name of the action method that I wanted to be called<br />

asynchronously. In the example, this was the GetPeopleData action, which generates a partial view containing a fragment<br />

of HTML.<br />

One problem with this approach is that it doesn’t work well if the user has disabled JavaScript (or is using a browser that<br />

doesn’t support it). In such cases, when the user submits the form, the browser display discards the current HTML page and<br />

replaces it with the fragment returned by the target action method. The effect can be seen in Figure 23-4.<br />

Figure 23-4. The effect of using the Ajax.BeginForm helper without browser JavaScript support<br />

Note I used Google Chrome for this figure because it makes it easy to toggle JavaScript.<br />

The simplest way to address this problem is to use the AjaxOptions.Url property to specify the target URL for the<br />

asynchronous request rather than specifying the action name as an argument to the Ajax.BeginForm method, as shown in<br />

Listing 23-11.<br />

Listing 23-11. Ensuring Gracefully Degrading Forms in the GetPeople.cshtml File<br />

@using HelperMethods.Models<br />

@model string<br />

@{<br />

ViewBag.Title = "GetPeople";<br />

Layout = "/Views/Shared/_Layout.cshtml";<br />

AjaxOptions ajaxOpts = new AjaxOptions {<br />

UpdateTargetId = "tableBody",<br />

616

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!