簡體   English   中英

Ajax sending null values to Controller even though I can see the value isn't null in Ajax

[英]Ajax sending null values to Controller even though I can see the value isn't null in Ajax

所以我的問題是整個事情都有效,我的調試語句正在我家 controller 中從 Ajax 調用中觸發,但 changeRole(string role) 中的角色參數每次都是 null。 誰能幫我弄清楚為什么?

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>
}

controller (HomeController.cs) 中的代碼

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

只需刪除 submit_changeRole function 中的contentType: "application/json"代碼。

contentType 是您從 ajax 發送到 controller 的數據類型,此處為application/json; 是常見的, application/x-www-form-urlencoded; charset=UTF-8 application/x-www-form-urlencoded; charset=UTF-8是默認值。

你當前傳遞的格式是默認格式而不是json格式,所以在controller中無法接收到值。

修改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}"
}

結果如下:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM