I want to make my Actions in Controllers more flexible. I mean that common Action usually returns:
...
return View("someView");
or, for example, if Ajax:
...
return Json(new {result="ok"});
What I want is to make my Actions more "multipurpose". For example, I made my UI layer based on simple non-Ajax requests, then I decided to make it more user-friendly and added some Ajax. That way I must correct a little a lot of Actions to return Json.
The most simplest (and probably the worst) way to avoid such things is to write the following code in every (or almost every) Action:
if (Request.IsAjaxRequest) {
return Json(new {result="ok"});
}
else {
return View("someView")
}
But of course such method completely conflicts with DRY's principles.
So I want to find the good practice to achieve that "multipurposing".
One way is to write some helper method like that:
public ActionResult CheckForAjax(ActionResult result)
{
return ActionResult(result, Json(new {result="ok"}));
}
public ActionResult CheckForAjax(ActionResult result, Json json)
{
if (Request.IsAjaxRequest) {
return json;
}
else {
return result;
}
}
Such way I can call helpers in Actions:
return CheckForAjax(View(...));
or
return CheckForAjax(View(...), Json(new {myCustomJson="hi"});
But I don't know if it's good way or just reinventing some bicycle :) Maybe it's better to use Actions Filters? But I don't know how to pass custom Json to that filter...
Thank you for any suggestions