如何从MVC控制器返回Json对象来查看

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15196528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:46:24  来源:igfitidea点击:

How to return Json object from MVC controller to view

asp.net-mvcjson

提问by Purushoth

I am doing an MVC application where i need to pass json object from controller to view.

我正在做一个 MVC 应用程序,我需要将 json 对象从控制器传递到视图。

var dictionary = listLocation.ToDictionary(x => x.label, x => x.value);
return Json(new { values = listLocation}, JsonRequestBehavior.AllowGet);

The above code i am using in my controller , now when i deploy the view page its opening a download dialog in my browser , when open the file it gives me json object as i needed format.

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

Now i want to return my view page also want to access the json object in the view page. how can i do that.

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

回答by Daniel Liuzzi

When you do return Json(...)you are specifically telling MVC not to use a view, and to serve serialized JSON data. Your browser opens a download dialog because it doesn't know what to do with this data.

当你这样做时,return Json(...)你特别告诉 MVC不要使用 view,并提供序列化的 JSON 数据。您的浏览器会打开一个下载对话框,因为它不知道如何处理这些数据。

If you instead want to return a view, just do return View(...)like you normally would:

如果你想返回一个视图,return View(...)就像往常一样:

var dictionary = listLocation.ToDictionary(x => x.label, x => x.value);
return View(new { Values = listLocation });

Then in your view, simply encode your data as JSON and assign it to a JavaScript variable:

然后在您的视图中,只需将您的数据编码为 JSON 并将其分配给一个 JavaScript 变量:

<script>
    var values = @Html.Raw(Json.Encode(Model.Values));
</script>


EDIT

编辑

Here is a bit more complete sample. Since I don't have enough context from you, this sample will assume a controller Foo, an action Bar, and a view model FooBarModel. Additionally, the list of locations is hardcoded:

这是一个更完整的示例。由于我没有从您那里获得足够的上下文,因此本示例将假定一个控制器Foo、一个操作Bar和一个视图模型FooBarModel。此外,位置列表是硬编码的:

Controllers/FooController.cs

控制器/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);
    }
}

Models/FooBarModel.cs

模型/FooBarModel.cs

public class FooBarModel
{
    public IEnumerable<SelectListItem> Locations { get; set; }
}

Views/Foo/Bar.cshtml

视图/Foo/Bar.cshtml

@model MyApp.Models.FooBarModel

<script>
    var locations = @Html.Raw(Json.Encode(Model.Locations));
</script>

By the looks of your error message, it seems like you are mixing incompatible types (i.e. Ported_LI.Models.Locatio??nand MyApp.Models.Location) so, to recap, make sure the type sent from the controller action side match what is received from the view. For this sample in particular, new FooBarModelin the controller matches @model MyApp.Models.FooBarModelin the view.

从您的错误消息的外观来看,您似乎混合了不兼容的类型(即Ported_LI.Models.Locatio??nMyApp.Models.Location),因此,回顾一下,确保从控制器操作端发送的类型与从视图接收的类型相匹配。特别是对于这个示例,new FooBarModel在控制器中匹配@model MyApp.Models.FooBarModel视图。

回答by Darin Dimitrov

You could use AJAX to call this controller action. For example if you are using jQuery you might use the $.ajax()method:

您可以使用 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>

回答by nirav savaliya

<script type="text/javascript">
jQuery(function () {
    var container = jQuery("\#content");
    jQuery(container)
     .kendoGrid({
         selectable: "single row",
         dataSource: new kendo.data.DataSource({
             transport: {
                 read: {
                     url: "@Url.Action("GetMsgDetails", "OutMessage")" + "?msgId=" + msgId,
                     dataType: "json",
                 },
             },
             batch: true,
         }),
         editable: "popup",
         columns: [
            { field: "Id", title: "Id", width: 250, hidden: true },
            { field: "Data", title: "Message Body", width: 100 },
           { field: "mobile", title: "Mobile Number", width: 100 },
         ]
     });
});

回答by nirav savaliya

$.ajax({
    dataType: "json",
    type: "POST",
    url: "/Home/AutocompleteID",
    data: data,
    success: function (data) {
        $('#search').html('');
        $('#search').append(data[0].Scheme_Code);
        $('#search').append(data[0].Scheme_Name);
    }
});