我正在做一个 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.Location
和 MyApp.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/