Combining actionresult and jsonresult

1.3k Views Asked by At

I want to do this:

   public ActionResult Details(int id)
    {
        Object ent = new{ prop1 = 1, prop2 = 2};
        if (Request.AcceptTypes.Contains("application/json"))
         return Json(ent, JsonRequestBehavior.AllowGet);

        ViewData.Model = ent;
        return View();
    }

But wonders if there isn't a better way (and build in) to detect an incoming jsonrequest, similar to IsAjaxRequest. I would want to use the same url, so preferably don't want to deal with format extensions, like ".json", ".html" etc.

Also I don't want to have a different url for the jsonrequest and the normal web request that returns a view.

1

There are 1 best solutions below

0
On BEST ANSWER

Using ActionFilterAttribute for your BaseController. and inherit all other controllers from BaseController

[IsJsonRequest]
public abstract class BaseController : Controller
{
   public bool IsJsonRequest { get; set; }
}

The ActionFilterAttribute
public class IsJsonRequest: ActionFilterAttribute  
{  
    public override void OnActionExecuting(ActionExecutingContext filterContext)  
    { 
        var myController = filterContext.Controller as MyController;
        if (myController != null)
        {

            if (filterContext.HttpContext.Request.AcceptTypes.Contains("application/json"))
            {
                myController.IsJsonRequest = true;
            }
            else
            {
                myController.IsJsonRequest = false;
            }
        }
    }
}

public class TestController : BaseController
{
    public ActionResult Details(int id)
    {
          if (IsJsonRequest)
               return Json Data
          else
               return view
    }
}