ASP.NET MVC 4 in Action - Manning Publications
ASP.NET MVC 4 in Action - Manning Publications
ASP.NET MVC 4 in Action - Manning Publications
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
110 CHAPTER 7 Ajax <strong>in</strong> <strong>ASP</strong>.<strong>NET</strong> <strong>MVC</strong><br />
Figure 7.2 The browser goes directly to the Privacy Policy page if JavaScript is disabled.<br />
gracefully degrade to its orig<strong>in</strong>al behavior and <strong>in</strong>stead send the user to the privacy policy<br />
page without us<strong>in</strong>g Ajax, as shown <strong>in</strong> figure 7.2.<br />
Unfortunately, this page doesn’t look very nice. We are currently render<strong>in</strong>g this<br />
page as a partial view <strong>in</strong> order to strip away the additional page chrome (added by our<br />
application’s layout) so that it can be easily <strong>in</strong>serted <strong>in</strong>to the DOM by our Ajax request.<br />
However, <strong>in</strong> the case where JavaScript is disabled, it would be nice to cont<strong>in</strong>ue to<br />
<strong>in</strong>clude the page layout and associated styl<strong>in</strong>g. Thankfully, it is easy to modify our<br />
PrivacyPolicy action to handle this scenario.<br />
List<strong>in</strong>g 7.4 Us<strong>in</strong>g IsAjaxRequest to modify action behavior<br />
public <strong>Action</strong>Result PrivacyPolicy()<br />
{<br />
if(Request.IsAjaxRequest()) <br />
Check if <strong>in</strong>voked <br />
{ B through Ajax<br />
return PartialView();<br />
}<br />
}<br />
return View();<br />
The PrivacyPolicy action now checks to see whether the action has been requested<br />
via Ajax or not by call<strong>in</strong>g the IsAjaxRequest extension method on the controller’s<br />
Request property B. If this returns true, then the action has been called by an Ajax<br />
request, <strong>in</strong> which case the view should be rendered as a partial; if the page has not<br />
been called by an Ajax request, it returns a normal view.<br />
Now, when you click the l<strong>in</strong>k with JavaScript disabled, the page is rendered with<br />
the correct layout, as shown <strong>in</strong> figure 7.3.