如何从MVC控制器返回Json对象来查看

2023-12-23

我正在做一个 MVC 应用程序,我需要将 json 对象从控制器传递到视图。

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

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

现在我想返回我的视图页面也想访问视图页面中的json对象。我怎样才能做到这一点。


当你这样做时return Json(...)你专门告诉MVC不使用视图,并提供序列化的 JSON 数据。您的浏览器会打开一个下载对话框,因为它不知道如何处理这些数据。

如果你想返回一个视图,只需这样做return View(...)像平常一样:

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

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

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

EDIT

这是更完整的示例。由于我没有从您那里获得足够的上下文,因此该示例将假设一个控制器Foo, 一种行为Bar,和一个视图模型FooBarModel。此外,位置列表是硬编码的:

控制器/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; }
}

视图/Foo/Bar.cshtml

@model MyApp.Models.FooBarModel

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

从错误消息的外观来看,您似乎正在混合不兼容的类型(即Ported_LI.Models.Locatio‌​n and MyApp.Models.Location)因此,回顾一下,请确保从控制器操作端发送的类型与从视图接收到的类型相匹配。特别是对于这个样本,new FooBarModel在控制器匹配@model MyApp.Models.FooBarModel视图中。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从MVC控制器返回Json对象来查看 的相关文章

随机推荐