ASP.NET MVC Tip: Got an Ajax Request?

Job-related I’m diving into this ASP.NET MVC stuff currently and will give you at this point some posts on that in the nearer future. Just for now: I like ASP.NET MVC and how MS implemented the core concepts. It’s clean, testable, flexible and extensible. Many things have changed since beyond standard ASP.NET…

Currently I’m becoming inspired by the Ajax Helpers, which ship with ASP.NET MVC. With Ajax.BeginForm(), Ajax.ActionLink() and Ajax.RouteLink() there currently (ASP.NET MVC Beta 1) exist three extension methods, which one can use after integrating the Microsoft Ajax script libraries in his page and which provide basic Ajax functionality.

At the moment I’m using Ajax.ActionLink() in my project to reload parts of my page, if the user clicks on a link. Especially I’m reloading data asynchronously, which the user changed through his click. That’s working pretty perfect for me, additionally I can serve a Confirm-Message via the AjaxOption „Confirm„, which is presented to the user before executing an action and over which the user can canel an action, too.

There’s one problem for me in this case: with the ActionLink ASP.NET MVC calls an Controller-Action. That’s happening via a special URL, which is mapped by the ASP.NET MVC routing system to an action. This action delivers with PartialView() the data (View), which are injected in the existing page with the aid of Ajax. The problem is: the user can pass this URL directly in his browser too and then he gets only those partial data in response, but not the whole page as in the case when he’s using the Ajax-ActionLink.

Some googling and testing yielded two ways for resolving this problem:

1st) One action with discrimination of the request type

First of all it’s possible to create an action, which can be invoked through both the Ajax ActionLink and the user through an URL in his browser. After including the namespace „System.Web.Mvc.Ajax“ one can use the extension method „Request.IsMvcAjaxRequest()“ in his controller action, with which it’s possible to check if the current request is coming from an ASP.NET MVC Ajax helper. Accordingly you are able to return the PartialView (on an Ajax request) or the complete view of your data (in case there’s no Ajax request). This is looking roughly as follows:

using System.Web.Mvc;
using System.Web.Mvc.Ajax;
...

namespace MyNamespace
{
    public class MyController : Controller 
    {
        ...
        public ActionResult MyAction(...) 
        {
            if(Request.IsMvcAjaxRequest()) 
            {
                ...
                return PartialView("MyPartialView", myPartialModel);
            } 
            else 
            {
                ...
                return View("MyCompleteView", myCompleteModel);
            }
        }
    }
}

Is this solution pretty? Well… Kevin Hoffman is criticizing the additional discrimination of the request type in the controller. Especially it’s coming out that Kevin sees the MVC principle violated, because this discrimination is going beyond the responsibility of a contoller (the following quote refers to an older ASP.NET MVC release, where there was an AjaxController with an IsAjaxRequest property):

MVC is all about proper separation of concerns. There’s one line of code in the sample that I think is violating that, and that’s the IsAjaxRequest property. This all smacks of someone attempting to make the MVC framework feel more like the old Postback world and quite frankly, the old postback world can eat my shorts. The controller, IMHO, is just a controller. It should not ever have to determine if it is rendering Ajax or rendering Regular. Ajax or regular HTML is a view decision not a controller decision. The job of the controller is to fetch the appropriate data required for rendering a view, and then pick the view to render.

Strongly taken I agree with Kevin from the architectural point of view. The view should be responsible to decide how some data is displayed, the controller should only deliver this data. On the other hand side my own individual opinion is that the controller should be able to decide, to which view it’s sending the data it fetches. Many controllers are doing so… e.g. they are calling an error page instead of the actual view if something goes wrong or they are redirecting to other views depending on the count of the received data. The only thing I’m worried about in this case is that the decision „Ajax-call or not“ is design-oriented and does not depend on data, which is fetched in the controller action itself, but which depends on the initial request. Though I’m not worried much about this, I’ve worked out another solution, which I’m coming up with in the following section…

2nd) Two actions with attributation

If you want to avoid a discrimination by „IsMvcAjaxRequest()„, you have to implement a second action. A first action „MyAction“ can then be called by the user via his browser and will return the complete view, where the second action -named e.g. „MyActionAjax„- could return a partial view, which is relevant for the Ajax request. This is looking as follows:

using System.Web.Mvc;
...

namespace MyNamespace 
{
    public class MyController : Controller 
    {
        ...
        public ActionResult MyAction(...) 
        {
            return View("MyCompleteView", myCompleteModel);
        }

        public ActionResult MyActionAjax(...) 
        {
            return PartialView("MyPartialView", myPartialModel);
        }
    }
}

Please identify that the basic problem still persists: the user can call „MyActionAjax“ via his browser. And here comes the trick: we’ll attribute „MyActionAjax()„, thus refusing the access. I’ve written a filter attribute, which is dealing with this:

using System.Web.Mvc;
...

namespace SDX.xMedia.mvc.Presentation.Common
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public sealed class MvcAsyncPostAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext != null && filterContext.HttpContext != null)
            {
                if (!IsMvcAsyncPost(filterContext.HttpContext.Request))
                    filterContext.Cancel = true;
            }
        }

        private bool IsMvcAsyncPost(HttpRequestBase request)
        {
            if (request == null)
                return false;

            return request["__MVCASYNCPOST"] == "true";
        }
    }
}

In this case I’m walking by foot. The Ajax helpers from ASP.NET MVC are setting the request parameter „__MVCASYNCPOST“ when performing an Ajax request. Further the extension method „Request.IsMvcAjaxRequest()“ is implemented in a way, which is only querying this value. Here is the current implementation from the ASP.NET MVC project:

public static bool IsMvcAjaxRequest(this HttpRequestBase request)
{
    if (request == null)
    {
        throw new ArgumentNullException("request");
    }
    return (request["__MVCASYNCPOST"] == "true");
}

Thus of course I can use this method for my request:

using System.Web.Mvc;
using System.Web.Mvc.Ajax;
...

namespace SDX.xMedia.mvc.Presentation.Common
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public sealed class MvcAsyncPostAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext != null && filterContext.HttpContext != null && filterContext.HttpContext.Request != null)
            {
                if (!filterContext.HttpContext.Request.IsMvcAjaxRequest())
                    filterContext.Cancel = true;
            }
        }
    }
}

By the way: IAuthorizationFilter has been implemented, because only in this way I was able to cancel the execution of the action in the first place ( filterContext.Cancel = true; ). Now with this attribute it’s possible to mark the „Ajax-only“ action and this way to prohibit the access through the browser:

using System.Web.Mvc;
...

namespace MyNamespace 
{
    public class MyController : Controller
    {
        ...
        public ActionResult MyAction(...)
        {
            return View("MyCompleteView", myCompleteModel);
        }

        [MvcAsyncPost]
        public ActionResult MyActionAjax(...)
        {
            return PartialView("MyPartialView", myPartialModel);
        }
    }
}

Now which way is prettier? Architecturally I like the second variant with regard to the separation of concerns principle which lets the controller do the stuff it should do. But there is one unaesthetic point in my eyes: the Ajax ActionLink is referencing to the action „MyActionAjax()“ and this link is delivered to the user by his browser. The user could be confused when he wants to share this link with one of his friends and has no direct access to the controller action, which stands behind this url. Thus from a user’s point of view the first solution makes more sense, but there has to be a trade-off as the case arises and I’m agog about your thoughts.

Update for the second solution:

My problem with the second solution was the action-link, which is pointing to MyActionAjax() and thus provided to the user. Now I’ve worked out a quick and dirty work-around for that (and guess what: no I don’t like it). I’m setting up my own RouteHandler in the following way:

class AjaxRouteHandler : MvcRouteHandler
{
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        if (requestContext.HttpContext.Request.IsMvcAjaxRequest())
            requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"] + "Ajax";

        return base.GetHttpHandler(requestContext);
    }
}

Now you can set up your routes with this route handler:

RouteTable.Routes.Add(
    new Route("{Controller}/{Action}/{id}",
    new RouteValueDictionary(new { Controller = "MyController", id = (int?)null }),
    new AjaxRouteHandler()));

What’s done: if there is no Ajax request, then the „normal“ action will be invoked (e.g. „MyAction“). On an Ajax-request instead there will be called the action „MyActionAjax“ automatically. Note that the programmer has to be responsible for the availability of this action pair. The benefit of that: you can provide „MyAction“ in your Ajax-ActionLink or call it via your browser and share the url with your friends. The route handler decides whether to invoke MyAction or MyActionAjax. Thus the responsibility for deciding if we’ve got an Ajax request comes out from the controller into the route handler. Please remember that I don’t have anything against having this piece of code in my controller, I’m just here to show some other way for solving this problem…

kick it on DotNetKicks.com

2 Gedanken zu „ASP.NET MVC Tip: Got an Ajax Request?“

  1. Nice post. Personally I do like the attribute version better because it clearly states the intention rather than polluting the code with the implementation.
    Also I’d like to point out that arguing that either solution introduces view related logic into the controller is a valid point; however it is the sad truth (IMHO) that this will at one point happen anyway. Picking the view is the first „fall of man“, picking the data to be presented (which may be as view specific as it comes) follows shortly thereafter. Even the very functionality made available by the controller is at the end view specific, for it reflects the capability of the UI technology.

    PS: I happend to be the first one to kick you 😉
    PPS: And I took the liberty to add you to my blogroll.

    You may invite me for a coffee (it’s free anyway ;-))

Kommentare sind geschlossen.