在执行此操作时,
return Json(...)您明确地告诉MVC 不要使用view
并提供序列化的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.Enpre(Model.Values));</script>
编辑
这是更完整的示例。由于我没有足够的上下文信息,因此本示例将假定一个控制器
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.Enpre(Model.Locations));</script>
从错误消息的外观来看,似乎您正在混合使用不兼容的类型(例如
Ported_LI.Models.Location和
MyApp.Models.Location),因此,概括地说,请确保从控制器操作端发送的类型与从视图接收的类型匹配。特别是对于此样本,
newFooBarModel在控制器
@model MyApp.Models.FooBarModel视图中进行匹配。



