我正在做一个MVC应用程序,我需要将json对象从控制器传递到视图.
var dictionary = listLocation.ToDictionary(x => x.label, x => x.value);
return Json(new { values = listLocation}, JsonRequestBehavior.AllowGet);
Run Code Online (Sandbox Code Playgroud)
上面的代码我在我的控制器中使用,现在当我部署视图页面时,它在我的浏览器中打开一个下载对话框,打开文件时它给了我json对象,因为我需要格式.
现在我想返回我的视图页面也想访问视图页面中的json对象.我怎样才能做到这一点.
Dan*_*zzi 58
当你这样做时,return Json(...)你特别告诉MVC 不要使用视图,并提供序列化的JSON数据.您的浏览器会打开一个下载对话框,因为它不知道如何处理这些数据.
如果您想要返回一个视图,return View(...)就像通常那样:
var dictionary = listLocation.ToDictionary(x => x.label, x => x.value);
return View(new { Values = listLocation });
Run Code Online (Sandbox Code Playgroud)
然后在您的视图中,只需将数据编码为JSON并将其分配给JavaScript变量:
<script>
var values = @Html.Raw(Json.Encode(Model.Values));
</script>
Run Code Online (Sandbox Code Playgroud)
编辑
这是一个更完整的样本.由于我没有足够的上下文,因此该示例将采用控制器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);
}
}
Run Code Online (Sandbox Code Playgroud)
型号/ FooBarModel.cs
public class FooBarModel
{
public IEnumerable<SelectListItem> Locations { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
查看/美孚/ Bar.cshtml
@model MyApp.Models.FooBarModel
<script>
var locations = @Html.Raw(Json.Encode(Model.Locations));
</script>
Run Code Online (Sandbox Code Playgroud)
根据您的错误消息的外观,您似乎混合了不兼容的类型(即Ported_LI.Models.Locatio??n和MyApp.Models.Location),因此,请回顾一下,确保从控制器操作端发送的类型与从视图接收的类型相匹配.特别是对于此示例,new FooBarModel在控制器中匹配@model MyApp.Models.FooBarModel视图.
您可以使用 AJAX 来调用此控制器操作。例如,如果您使用 jQuery,您可以使用以下$.ajax()方法:
<script type="text/javascript">
$.ajax({
url: '@Url.Action("NameOfYourAction")',
type: 'GET',
cache: false,
success: function(result) {
// you could use the result.values dictionary here
}
});
</script>
Run Code Online (Sandbox Code Playgroud)