Asp.net-Mvc
為 JsonResult 呼叫 @Html.Action 會更改我在父模板中的響應類型
我有以下控制器:
public class HelloController { public ActionResult Index() { return View() } public ActionResult Hello() { return Json(new{ greeting = "hello, world!" }, JsonRequestBehavior.AllowGet); } }然後,在裡面
Index.cshtml:...html stuffs <script type="text/javascript"> alert("@Html.Action("Hello")"); </script>我發現,當在我的瀏覽器中訪問這個 url 時,響應內容類型會
application/json; charset=utf-8導致瀏覽器將 html 呈現為字元串而不是…網頁。解決這個問題的最佳方法是什麼?
原因是所有
Html.Action呼叫都是直接執行的。就像是:
- 索引被稱為
- 查看結果執行
- 執行hello動作,set的ContextType
- 返回索引視圖結果
- 瀏覽器顯示頁面
你有兩個選擇:
- 打破生成“Hello world!”的邏輯 進入正常 C# 類並直接在 Index 控制器操作中呼叫它
- 通過 ajax 載入 Hello 動作,然後顯示
alert.選項1
public class HelloController { YourBusiness _yb; public HelloController(YourBusiness yb) { _yb = yb; } public ActionResult Index() { return View(yb.GenerateHello()) } // used for everything but Index public ActionResult Hello() { return Json(new{ greeting = yb.GenerateHello() }, JsonRequestBehavior.AllowGet); } } public class YourBusiness { public string GenerateHello() { return "Hello wolrd!"; } }選項 2
<script type="text/javascript"> $.get('@Url.Action("Hello")', function(response) { alert(response.greeting); } </script>邊注
Internet Explorer 在記憶體方面非常激進。JSON 響應將被更改。因此,我建議您也不要為 JSON 操作指定記憶體:
[OutputCache(Duration = 0, NoStore = true)] public ActionResult Hello() { return Json(new{ greeting = "hello, world!" }, JsonRequestBehavior.AllowGet); }
只需使用的重載
Json(...)來設置正確的內容類型。public class HelloController { public ActionResult Index() { return View() } public ActionResult Hello() { return Json(new{ greeting = "hello, world!" }, "text/html", JsonRequestBehavior.AllowGet); } }