如何从MVC控制器返回Json对象?

时间:2022-10-18 14:01:37

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对象。我怎么做呢。

4 个解决方案

#1


57  

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.

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

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

如果你想要返回一个视图,就像你通常会做的那样返回视图(…):

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、一个操作条和一个视图模型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‌​n and 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 FooBarModel in the controller matches @model MyApp.Models.FooBarModel in the view.

通过您的错误消息的外观,似乎您正在混合不兼容的类型(例如,Ported_LI.Models)。地区‌n和MyApp.Models.Location)所以,回顾一下,确保类型发送从控制器动作匹配收到的观点是什么。对于这个示例,控制器中的新FooBarModel与@model MyApp.Models匹配。FooBarModel视图中。

#2


4  

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>

#3


0  

<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 },
         ]
     });
});

#4


-2  

$.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);
    }
});

#1


57  

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.

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

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

如果你想要返回一个视图,就像你通常会做的那样返回视图(…):

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、一个操作条和一个视图模型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‌​n and 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 FooBarModel in the controller matches @model MyApp.Models.FooBarModel in the view.

通过您的错误消息的外观,似乎您正在混合不兼容的类型(例如,Ported_LI.Models)。地区‌n和MyApp.Models.Location)所以,回顾一下,确保类型发送从控制器动作匹配收到的观点是什么。对于这个示例,控制器中的新FooBarModel与@model MyApp.Models匹配。FooBarModel视图中。

#2


4  

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>

#3


0  

<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 },
         ]
     });
});

#4


-2  

$.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);
    }
});