为JsonResult调用@ Html.Action会更改父模板中的响应类型

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呈现为字符串而不是...网页.

什么是最好的解决方法?

hwi*_*ers 7

只需使用重载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)


jga*_*fin 5

这样做的原因是所有Html.Action调用都直接执行。就像是:

  1. 索引称为
  2. 查看结果执行
  3. 已执行Hello操作,设置了ContextType
  4. 返回索引视图结果
  5. 浏览器显示页面

您有两种选择:

  1. 打破产生“ Hello world!”的逻辑。到常规C#类中,然后直接在Index controller action中调用它
  2. 通过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!";
    }
}
Run Code Online (Sandbox Code Playgroud)

选项2

<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)