当你这样做时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.Location
and MyApp.Models.Location
)因此,回顾一下,请确保从控制器操作端发送的类型与从视图接收到的类型相匹配。特别是对于这个样本,new FooBarModel
在控制器匹配@model MyApp.Models.FooBarModel
视图中。