结合actionresult和jsonresult

时间:2011-02-25 13:50:23

标签: json asp.net-mvc-2 actionresult

我想这样做:

   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();
    }

但是想知道是否有更好的方法(和内置)来检测传入的jsonrequest,类似于IsAjaxRequest。我想使用相同的URL,所以最好不要处理格式扩展,如“.json”,“。html”等。

此外,我不希望为jsonrequest和返回视图的普通Web请求设置不同的URL。

1 个答案:

答案 0 :(得分:2)

为BaseController使用ActionFilterAttribute。并继承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
    }
}