当你return Json(...)你特别告诉MVC 不要使用视图 ,并为序列化的JSON数据提供服务。 您的浏览器会打开一个下载对话框,因为它不知道如何处理这些数据。
如果你想要返回一个视图,只要像你一样return View(...) :
var dictionary = listLocation.ToDictionary(x => x.label, x => x.value); return View(new { Values = listLocation });
然后在您的视图中,只需将数据编码为JSON并将其分配给JavaScriptvariables即可:
编辑
这里是一个更完整的示例。 由于我没有足够的上下文,这个示例将假设一个控制器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 Locations { get; set; } }
查看/美孚/ Bar.cshtml
@model MyApp.Models.FooBarModel
通过看你的错误消息,似乎你是混合不兼容的types(即Ported_LI.Models.Location和MyApp.Models.Location ),所以,总结一下,确保从控制器动作端发送的types匹配是什么从视图中收到。 对于此示例,控制器中的@model MyApp.Models.FooBarModel在视图中匹配@model MyApp.Models.FooBarModel 。