asp.net-mvc - 如何从 MVC Controller 返回 Json 对象以查看

标签 asp.net-mvc json

我正在做一个 MVC 应用程序,我需要将 json 对象从 Controller 传递到 View 。

var dictionary = listLocation.ToDictionary(x => x.label, x => x.value);
return Json(new { values = listLocation}, JsonRequestBehavior.AllowGet);

上面的代码我在我的 Controller 中使用,现在当我部署 View 页面时,它会在我的浏览器中打开一个下载对话框,当打开文件时,它会根据我需要的格式给我 json 对象。

现在我想返回我的 View 页面也想访问 View 页面中的 json 对象。我该怎么做。

最佳答案

当您执行 return Json(...) 时,您是在明确告诉 MVC 不要使用 View ,并提供序列化的 JSON 数据。您的浏览器会打开一个下载对话框,因为它不知道如何处理这些数据。

如果您想返回一个 View ,只需像往常一样执行 return View(...):

var dictionary = listLocation.ToDictionary(x => x.label, x => x.value);
return View(new { Values = listLocation });

然后在您的 View 中,只需将您的数据编码为 JSON 并将其分配给 JavaScript 变量:

<script>
    var values = @Html.Raw(Json.Encode(Model.Values));
</script>

编辑

这里有一个更完整的示例。由于我没有从你那里得到足够的上下文,这个示例将假定一个 Controller Foo、一个 Action Bar 和一个 View 模型 FooBarModel。此外,位置列表是硬编码的:

Controllers/FooController.cs

public class FooController : Controller
{
    public ActionResult Bar()
    {
        var locations = new[]
        {
            new SelectListItem { Value = "US", Text = "United States" },
            new SelectListItem { Value = "CA", Text = "Canada" },
            new SelectListItem { Value = "MX", Text = "Mexico" },
        };

        var model = new FooBarModel
        {
            Locations = locations,
        };

        return View(model);
    }
}

模型/FooBarModel.cs

public class FooBarModel
{
    public IEnumerable<SelectListItem> Locations { get; set; }
}

Views/Foo/Bar.cshtml

@model MyApp.Models.FooBarModel

<script>
    var locations = @Html.Raw(Json.Encode(Model.Locations));
</script>

从您的错误消息来看,您似乎在混合不兼容的类型(即 Ported_LI.Models.Locatio‌​nMyApp.Models.Location)所以,回顾一下,确保从 Controller 操作端发送的类型与从 View 接收到的类型相匹配。特别是对于这个示例, Controller 中的 new FooBarModel 与 View 中的 @model MyApp.Models.FooBarModel 匹配。

关于asp.net-mvc - 如何从 MVC Controller 返回 Json 对象以查看,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15196528/

相关文章:

asp.net-mvc - 使用 ASP.NET MVC 支持 "Expect: 100-continue" header

c# - EF 错误地映射 ID 属性

jquery - 无法缩进表中的 th 和 td 元素

c# - SignalR - 使用 UserID Provider 向用户发送消息

json - 使用 jq 将 Json 文件中的表格形式的元素相关联

c# - 如何从 JSON 字符串中删除特定的 JSON 属性

android - NSnull 类型的 JSON 值无法转换为 NSString

c# - 在 ASP.NET MVC 中使用 web.config 保护内容安全策略 header 列表

javascript - 使用 javascript 循环读取 JSON 数字数组

javascript - jQuery - 将 json 内容绑定(bind)到元素的简单方法?