DMa*_*yer 11 asp.net-mvc content-type jsonresult
我有以下控制器:
public class HelloController
{
public ActionResult Index()
{
return View()
}
public ActionResult Hello()
{
return Json(new{ greeting = "hello, world!" }, JsonRequestBehavior.AllowGet);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,里面Index.cshtml
:
...html stuffs
<script type="text/javascript">
alert("@Html.Action("Hello")");
</script>
Run Code Online (Sandbox Code Playgroud)
我发现,当我在浏览器中访问此URL时,响应内容类型会application/json; charset=utf-8
导致浏览器将html呈现为字符串而不是...网页.
什么是最好的解决方法?
只需使用重载Json(...)
来设置正确的内容类型.
public class HelloController
{
public ActionResult Index()
{
return View()
}
public ActionResult Hello()
{
return Json(new{ greeting = "hello, world!" }, "text/html", JsonRequestBehavior.AllowGet);
}
}
Run Code Online (Sandbox Code Playgroud)
这样做的原因是所有Html.Action
调用都直接执行。就像是:
您有两种选择:
alert
。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!";
}
}
Run Code Online (Sandbox Code Playgroud)
<script type="text/javascript">
$.get('@Url.Action("Hello")', function(response) {
alert(response.greeting);
}
</script>
Run Code Online (Sandbox Code Playgroud)
在缓存方面,Internet Explorer非常激进。JSON响应将被更改。因此,我建议您也不要为JSON操作指定任何缓存:
[OutputCache(Duration = 0, NoStore = true)]
public ActionResult Hello()
{
return Json(new{ greeting = "hello, world!" }, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3951 次 |
最近记录: |