2010-12-19 82 views
0

我有一個場景,我試圖使用jQuery模板插件來顯示我的MVC列表視圖中的數據列表。但是,我的列表是我的mvc應用程序的默認視圖。我想使用同一個動作來同時返回json數據和返回視圖。ASP.Net MVC列表操作返回Json數據

這是雙向獲取數據。有沒有辦法,只要我的動作被調用,我返回Json數據並使用模板插件來顯示數據。

回答

2

您可以測試操作的調用與AJAX然後返回JSON數據,如果不返回普通視圖:

public ActionResult Index() 
{ 
    var model = FetchModel(); 
    if (Request.IsAjaxRequest()) 
    { 
     return Json(model, JsonRequestBehavior.AllowGet); 
    } 
    return View(model); 
} 

當然,這if使你的控制器動作難看。這將是更好用行動過濾器,以避免重複在多個動作這樣的邏輯:

public class MyFilterAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuted(ActionExecutedContext filterContext) 
    { 
     base.OnActionExecuted(filterContext); 
     if (filterContext.HttpContext.Request.IsAjaxRequest()) 
     { 
      var viewResult = filterContext.Result as ViewResultBase; 
      if (viewResult != null) 
      { 
       if (viewResult.Model != null) 
       { 
        filterContext.Result = new JsonResult 
        { 
         Data = viewResult.Model, 
         JsonRequestBehavior = JsonRequestBehavior.AllowGet 
        }; 
       } 
      } 
     } 
    } 
} 

然後用這個屬性裝飾你的控制器:

[MyFilter] 
public ActionResult Index() 
{ 
    var model = FetchModel(); 
    return View(model); 
} 
+0

感謝您的答覆。但是,這仍然會有2次往返服務器,我想避免。我想通過List動作返回Json數據,並通過模板插件顯示它。任何幫助? – Ashish 2010-12-19 13:27:37

1

您對Darins偉大的答案評論使我相信你需要以下你的問題沒有真正解釋。

如果我沒有穿過我的電線,然後這是我的幫助......

您可以返回一個HTML視圖,還包括腳本標籤包含一個JSON對象。

創建的toJSON HTML輔助擴展e.g

public static class MvcViewExtensions 
    { 

    public static string toJson(this System.Web.Mvc.HtmlHelper helper, object obj) 
    { 
     JavaScriptSerializer serializer = new JavaScriptSerializer(); 
     return serializer.Serialize(obj); 
    } 
    } 

然後在您查看這樣的事情

<html> 

    ...other html stuff 

    <script> 

     var json = <%= Html.ToJson(Model.someProperty) %>; 
     //call to some js to do your templating 
     myapp.someTemplatingFunc(json); 

    </script> 
</html> 
+0

我正在嘗試與上面的代碼相同的Razor語法失敗。我試圖: var json = @ Model.ToJson(); – Ashish 2010-12-19 16:47:48

+0

好'失敗'對我沒有多大用處 - 你有更多的信息嗎?模型是否有ToJson方法? – redsquare 2010-12-19 19:43:52

+0

不,我有一個單獨的ToJson靜態類,正如你上面提到的那樣。然而,一旦編譯器命中@Model.ToJson(),它會拋出錯誤「'System.Collections.Generic.List '不包含'ToJson'的定義」 – Ashish 2010-12-20 11:03:44