Separate controller for ajax actionresults in asp.net mvc 3

For ajax, it calls actionresult. I think of two options.

  • Put the action results in the controller that is most suitable for their functions.
  • Make a separate controller for ajax calls

In the second approach, I can use separate files for functional separation of the controller and use a partial ajaxcontrollerclass in each file. The second option can be useful if there are some actionfilter attributes that I want to apply to actions other than the ajax action results, for example, the Authorize attribute can be applied to the result of a regular action. I can use the Ajaxonly attribute ajax actionresults to protect them
which option would prefer

+3
source share
1 answer

Why would you want to do that? For me, the controller is tied to a specific model, and not to a specific type of output format.

public ActionResult Users()
{
    var users = _repository.Find(); 
    var viewModel  = Mapper.Map(users); // automapper or similar
    return Request.IsAjax() ? Json(viewModel) : View(viewModel);
}

To respond to your update

It is better to create CustomAuthorizeAttributeone that checks if it is an ajax request or a regular request and does the correct authorization. Your controllers do not need to know how authorization is done.

+5
source

All Articles