我正在尝试从部分 View 中调用 Controller 操作 (JsonResult):
var departmentsViewJS = {
view: "accordion",
multi: true,
cols: @Html.Action("GetDepartmentsJson")
};
调用该操作,精彩的 Json 替换了输出中的 @Html.Action
,但整个 View (_Layout、View 和部分)以纯文本形式呈现到页面。如果我只用括号替换操作,如下所示:
var departmentsViewJS = {
view: "accordion",
multi: true,
cols: []
};
页面渲染得非常好(但没有那些列)。难道我们不允许在部分中做这样的事情吗?还是我在某个地方搞砸了?
以下是渲染输出的示例:
var departmentsViewJS = {
view: "accordion",
multi: true,
cols: [{"Id":25,"DocRoot":"Test","Name":"Test","DepartmentKeywords":null},{"Id":27,"DocRoot":"HumanResources","Name":"Human Resources","DepartmentKeywords":null}]
};
如果我将渲染的 Json 复制到 @Html.Action
上,页面也可以正常渲染。
最佳答案
发生这种情况是因为当您调用返回 JsonResult 的操作时,它将响应内容类型设置为 application/json。
您可以将 GetDepartmentsJson 的返回类型更改为字符串,并在服务器端将对象序列化为 json。
如果您不想更改 Controller ,则可以在 View 上进行更改
@{ var prevContentType = Html.ViewContext.HttpContext.Response.ContentType; }
var departmentsViewJS = {
view: "accordion",
multi: true,
cols: @Html.Action("GetDepartmentsJson"); }
};
@{ Html.ViewContext.HttpContext.Response.ContentType = prevContentType; }
关于asp.net-mvc - 从部分 View 调用操作时以纯文本形式查看渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27866318/