gpt4 book ai didi

asp.net-mvc - 为 JsonResult 调用 @Html.Action 会更改我在父模板中的响应类型

转载 作者:行者123 更新时间:2023-12-02 09:40:08 25 4
gpt4 key购买 nike

我有以下 Controller :

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>

我发现,当在浏览器中访问此网址时,响应内容类型为 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);
}
}

关于asp.net-mvc - 为 JsonResult 调用 @Html.Action 会更改我在父模板中的响应类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10543953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com