加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – ASP.NET MVC:View有时作为application / json而

发布时间:2020-12-16 09:51:31 所属栏目:asp.Net 来源:网络整理
导读:我有一个视图,我从中调用另一个视图在我的html中的脚本标记内呈现一些json: public ActionResult App(){ return View();}public JsonResult SomeJsonData(){ // ... here goes the code that generates the model return Json(model,JsonRequestBehavior.Al
我有一个视图,我从中调用另一个视图在我的html中的脚本标记内呈现一些json:

public ActionResult App()
{
  return View();
}

public JsonResult SomeJsonData()
{
  // ... here goes the code that generates the model
  return Json(model,JsonRequestBehavior.AllowGet);
}

在我的App.cshtml文件中我有这样的东西:

<script type='text/javascript'>
  var myJsonData = @Html.Action("SomeJsonData","MyController");
</script>

问题是有时当我在浏览器中重新加载页面时(现在使用Chrome 20)它显示所有标记,如果我转到开发人员工具中的网络选项卡,我可以看到页面请求的内容类型是“application / json”类型.如果我只是重新加载页面然后它正确加载(内容类型是“text / html”应该是).

有没有想过为什么会这样?或者我做错了什么?

解决方法

当您返回JsonResult时,您正在将响应Content-Type修改为application / json.因此,您首先调用App控制器操作,该操作返回一个View,并显然将Content-Type设置为text / html,并在返回的视图中调用SomeJsonData操作,该操作会破坏先前的内容类型并将其修改为application / json.当然最后一个赢了,这就是用户代理在一天结束时所看到的:application / json.

那么,这是如何进行的:

public ActionResult App()
{
    // ... here goes the code that generates the model
    var model = ...

    return View(model);
}

并在您的强类型视图中:

@model MyViewModel
<script type="text/javascript">
    var myJsonData = @Html.Raw(Json.Encode(Model));
</script>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读