11

我有以下控制器:

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

解决这个问题的最佳方法是什么?

4

3 回答 3

7

只需使用的重载Json(...)来设置正确的内容类型。

public class HelloController
{
    public ActionResult Index()
    {
        return View()
    }

    public ActionResult Hello()
    {
        return Json(new{ greeting = "hello, world!" }, "text/html", JsonRequestBehavior.AllowGet);
    }
}
于 2012-05-11T01:51:48.877 回答
5

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

  1. 索引被称为
  2. 查看结果执行
  3. 执行hello动作,set的ContextType
  4. 返回索引视图结果
  5. 浏览器显示页面

你有两个选择:

  1. 打破生成“Hello world!”的逻辑 进入常规 C# 类并直接在 Index 控制器操作中调用它
  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!";
    }
}

选项 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);
}
于 2012-05-11T05:13:33.590 回答
0

如果通过调用 Json() 方法返回 JsonResult,它不会返回网页。要返回一个页面,您需要通过调用 View 方法返回一个 ViewResult。你的方法应该有一个对应的视图模板

查看链接或链接

于 2012-05-11T01:38:21.260 回答