首页 > 解决方案 > 从json控制器结果ajax获取多个字符串

问题描述

我有一个按钮,使用 ajax 从表单中的文本字段向我的 mvc 控制器发送输入。我现在希望控制器将 2 个字符串作为 json 返回,并将这些字符串填充到 html 输入中。

控制器

[HttpPost]
    public ActionResult getName(string Name)
    {

        string SecondString = "secondString";

        return Json(Name, SecondString);
    }

看法

<script>
$(document).ready(function () {
    $("#btnGet").click(function () {
        $.ajax(
            {
                type: "POST", 
                url: "home/getName", 
                data: { 
                    Name: $("#txtName").val()
                },
                success: function (result) {
                    $('#FirstTextFieldToFill').val(result);
                    $('#SecondTextFieldToFill').val(result);

                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });

    });
});

标签: c#asp.net-mvc

解决方案


您错误地将参数分配Json()给返回响应的方法JsonResult,因为第二个参数是JsonRequestBehavioror contentType。您应该返回带有单个参数Controller.Json()的响应,如下所示:

[HttpPost]
public ActionResult GetName(string Name)
{
    string SecondString = "secondString";

    return Json(new { Name = Name, SecondString = SecondString });
}

然后修改您的 AJAX 调用以使用属性名称从响应中返回 2 个字符串:

$("#btnGet").click(function () {
    $.ajax({
        type: "POST", 
        url: "@Url.Action("GetName", "Home"), 
        data: { Name: $("#txtName").val() },
        success: function (result) {
            $('#FirstTextFieldToFill').val(result.Name);
            $('#SecondTextFieldToFill').val(result.SecondString);
        },
        failure: function (response) {
            alert(response.responseText);
        },
        error: function (response) {
            alert(response.responseText);
        }
    });
});

推荐阅读