加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何从MVC控制器返回Json对象到视图

发布时间:2020-12-15 19:10:27 所属栏目:asp.Net 来源:网络整理
导读:我做一个MVC应用程序,我需要传递json对象从控制器到视图。 var dictionary = listLocation.ToDictionary(x = x.label,x = x.value);return Json(new { values = listLocation},JsonRequestBehavior.AllowGet); 上面的代码我使用在我的控制器,现在当我部署
我做一个MVC应用程序,我需要传递json对象从控制器到视图。
var dictionary = listLocation.ToDictionary(x => x.label,x => x.value);
return Json(new { values = listLocation},JsonRequestBehavior.AllowGet);

上面的代码我使用在我的控制器,现在当我部署视图页面在我的浏览器中打开一个下载对话框,当打开文件,它给我的json对象作为我需要的格式。

现在我想返回我的视图页面也想访问视图页面中的json对象。我怎样才能做到这一点。

解决方法

当你返回Json(…)时,你特意告诉MVC不要使用视图,并提供序列化的JSON数据。您的浏览器打开一个下载对话框,因为它不知道如何处理这些数据。

如果你想要返回一个视图,只需返回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>

编辑

这里有一个更完整的示例。因为我没有足够的上下文,这个示例将假设一个控制器Foo,一个动作栏和一个视图模型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.Locatio n和MyApp.Models.Location),所以,重述,确保从控制器操作端发送的类型匹配什么从视图接收。对于这个示例,控制器中的新FooBarModel与视图中的@model MyApp.Models.FooBarModel匹配。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读