我有以下控制器:
公共类的HelloController{ 公众的ActionResult指数() { 返回查看() } 公众的ActionResult你好() { 返回JSON(新{=问候你好,世界!},JsonRequestBehavior.AllowGet); }}然后,在 Index.cshtml :
... HTML东西<脚本类型=文/ JavaScript的> 警报(@ Html.Action(你好));< / SCRIPT>什么我发现是,在我的浏览器去这个网址时,响应内容类型为应用程序/ JSON的;字符集= UTF-8 这会导致浏览器呈现HTML作为字符串而不是作为...网页。
什么是解决这个问题的最好方法?
解决方案之所以这是所有 Html.Action 调用是直接执行。是这样的:
您有两个选择:
选项2
<脚本类型=文/ JavaScript的> $获得(@ Url.Action(你好)',函数(响应){ 警报(response.greeting); }< / SCRIPT>边注
Internet Explorer中相当积极,当涉及到缓存。该JSON响应将被改变。因此,我建议你也指定没有缓存为JSON动作:
[的OutputCache(持续时间= 0,NoStore = TRUE)]公众的ActionResult你好(){ 返回JSON(新{=问候你好,世界!},JsonRequestBehavior.AllowGet);}I've got the following controller:
public class HelloController { public ActionResult Index() { return View() } public ActionResult Hello() { return Json(new{ greeting = "hello, world!" }, JsonRequestBehavior.AllowGet); } }Then, inside Index.cshtml:
...html stuffs <script type="text/javascript"> alert("@Html.Action("Hello")"); </script>What I'm finding is that, when going to this url in my browser, the response content type is application/json; charset=utf-8 which causes the browser to render the html as a string instead of as... a web page.
What's the best way to get around this?
解决方案The reason to this is that all Html.Action invocations are executed directly. Something like:
You got two options:
Option 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!"; } }Option 2
<script type="text/javascript"> $.get('@Url.Action("Hello")', function(response) { alert(response.greeting); } </script>Side note
Internet Explorer is quite aggressive when it comes to caching. The JSON responses will be changed. I therefore recommend that you also specify no cache for the JSON action:
[OutputCache(Duration = 0, NoStore = true)] public ActionResult Hello() { return Json(new{ greeting = "hello, world!" }, JsonRequestBehavior.AllowGet); }
更多推荐
呼吁JsonResult @ Html.Action改变父模板我响应类型
发布评论