【问题标题】:Ajax sending null values to Controller even though I can see the value isn't null in AjaxAjax 向 Controller 发送空值,即使我可以看到 Ajax 中的值不为空
【发布时间】:2020-10-13 01:51:38
【问题描述】:

所以我的问题是整个事情都有效,并且我的调试语句正在我的家庭控制器中从 Ajax 调用中触发,但是 changeRole(string role) 中的角色参数每次都是空的。谁能帮我弄清楚为什么?

Jquery/Ajax (changeRole.js)

$(function () {
    console.log("loaded");
})

function submit_changeRole(e, role) {
    e.preventDefault();
    $.ajax({
        url: "/Home/changeRole",
        method: "Post",
        data: {"role": role },
        contentType: "application/json",
        dataType: "json"
    }).done(function (result) {
        console.log("action taken: " + result);
        alert($("#b").text());
    }).fail(function (jqXHR, textStatus, errorThrown) {
        console.log("failed: ");
        console.log(jqXHR);
        console.log(textStatus);
        console.log(errorThrown);
    }).always(function () {
        console.log("but I will always do this");
    });
    return "{Success:true}"
}

视图中的代码 (index.cshtml)

<form>
    <button id="LAButton" onclick="submit_changeRole(event, 'LA');" formmethod="Post">LA</button>
</form>

@section Scripts {
        <script src="~/js/changeRole.js"></script>
}

控制器中的代码 (HomeController.cs)

[HttpPost]
public JsonResult changeRole(string role)
{
    Debug.WriteLine("User wants to be role: " + role);
    return Json(
        new
        {
            success = true,
        });
}

【问题讨论】:

    标签: jquery asp.net ajax asp.net-mvc asp.net-core


    【解决方案1】:

    只需删除 submit_changeRole 函数中的 contentType: "application/json" 代码即可。

    contentType 是你从 ajax 发送到控制器的数据类型,这里application/json; 是常见的,application/x-www-form-urlencoded; charset=UTF-8 是默认的。

    您当前传递的格式是默认格式,而不是 json格式,因此控制器无法接收到该值。

    修改js如下:

    function submit_changeRole(e, role) {
        e.preventDefault();
        $.ajax({
            url: "/Home/changeRole",
            method: "Post",
            data: {  "role" : role }, 
            dataType: "json"
        }).done(function (result) {
            console.log("action taken: " + result);
            alert($("#b").text());
        }).fail(function (jqXHR, textStatus, errorThrown) {
            console.log("failed: ");
            console.log(jqXHR);
            console.log(textStatus);
            console.log(errorThrown);
        }).always(function () {
            console.log("but I will always do this");
        });
        return "{Success:true}"
    }
    

    结果如下:

    【讨论】:

      猜你喜欢
      • 2021-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-26
      • 2014-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多