asp.net-mvc 如何使用 MVC 控制器返回 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9222559/
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-08 01:44:05  来源:igfitidea点击:

how to return JSON with MVC Controller

asp.net-mvc

提问by jvm

I am calling my controller method using .ajax. my controller method call web service which returns dictionary. now i need to return this and populate dropdown list. i am trying with return JSON and need to populate using success (response)

我正在使用 .ajax 调用我的控制器方法。我的控制器方法调用返回字典的 Web 服务。现在我需要返回它并填充下拉列表。我正在尝试返回 JSON 并需要使用成功(响应)进行填充

I am using MVC 1.0

我正在使用 MVC 1.0

        $.ajax(
            {
                url: 'LookupValue/',
                data: { 'sLookupIds': selectedtext },
                datatype: "json",
                traditional: true,
                success: function (data) {
                    alert(data.value);
                }
            });

thanks in advance.

提前致谢。

回答by jvm

In controller

在控制器中

    public JsonResult LookupValue(String sLookupIds)
    {

        SelectList olist = new SelectList(oDict, "key","value");

        return Json(olist);

  }

In view

在视图中

        $.ajax(
            {
                url: 'LookupValue/',
                data: { 'sLookupIds': selectedtext },
                datatype: "json",
                traditional: true,
                success: function (data) {
                    $.each(data, function (index, val) {
                        $('#lookup')
                        .append($("<option></option>")
                        .attr("value", val.Value)
                        .text(val.Text));
                        //ddHTML = ddHTML + "<option  value='" + val.Value + "'>'" + val.Texts + "'</option>";
                    });
                }
            });

回答by Esteban Araya

In your Actionin your Controller:

在你Action在你的Controller

return Json(data);

Where data is your object that you want serialiazed to JSON.

其中 data 是您想要序列化为 JSON 的对象。

If you want to use Json.NET, just override the Json method.

如果要使用 Json.NET,只需覆盖 Json 方法即可。