views:

30

answers:

1

In ASP.NET webforms I used to write AJAX apps where the client would communicate to the server using web services or page methods and JSON.

I'm new to ASP.NET MVC and have found that one could use web services or controller actions that use JSON. Are there other options? Should I use web services or controller actions and why?

+1  A: 

Most MVC apps use controller actions for Ajax actions.

I think the "why" is that you're leveraging your skillset and the MVC infrastructure. Everything you're doing in the app is following the MVC model, why not drop Ajax into it as well? It's just a very natural pattern.

On the server, I often find myself forgetting if an action is Ajax invoked or not. I think this is a very good thing. The method of invoking the action is a separate concern from what the action does. This is particularly true, when you're using progressive enhancement (Ajax for Javascript enabled, http post for non-js). Then the pattern looks something like below. I really like that I can forget about the communication mechanism and focus on what my app is supposed to do.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyProgressiveEnhancedAction(FormCollection form)
{
  // Handle Html Post

  if (!Request.IsAjaxRequest())
    return ActionViaHtmlPost();

  // Ajax Invocation

  ...

When I'm using this pattern I often find that I have a little bit of glue to abstract Ajax vs. Post and the rest (model, domain interactions, etc.) are common.

Rob