簡體   English   中英

MVC控制器方法參數始終為空

[英]MVC Controller Method Parameter Always Null

我的javascript函數調用我的MVC 4控制器,但參數始終為null。 這似乎是一個常見的問題,我嘗試了一些我研究過的東西,但沒有任何工作。 知道為什么它總是空的嗎?

我的javascript GetEntries()函數正確創建了一個顯示值的警報:

function GetEntries(firstLetter) {
    alert(firstLetter);
    $.post('/Home/GetEntries',
           firstLetter,
           EntriesReceived());
}

我的控制器方法斷點被命中:

public void GetEntries(string firstLetter)
{
    Debug.WriteLine(firstLetter);
}

但是,firstLetter始終為null。 我不知道該怎么做。

嘗試失敗:

我嘗試使用JSON.stringify發布。

function GetEntries(firstLetter) {
    alert(firstLetter);
    var firstLetterAsJson = JSON.stringify(firstLetter);
    $.post('/Home/GetEntries',
           { jsonData: firstLetterAsJson },
            EntriesReceived());
}

我嘗試將HttpPost屬性添加到我的控制器:

[HttpPost]
public void GetEntries(string firstLetter)
{
    Debug.WriteLine(firstLetter);
}

我嘗試將參數名稱更改為“id”以匹配我的路由映射:

[HttpPost]
public void GetEntries(string id)
{
    Debug.WriteLine(id);
}

以下應該有效

function GetEntries(firstLetter) {
    $.post('/Home/GetEntries', { firstLetter: firstLetter }, EntriesReceived);
}

還要注意EntriesReceived回調如何作為第三個參數傳遞給$.post函數。 在您的代碼中,您似乎正在調用函數( EntriesReceived() )而不是將其作為回調傳遞。 這里我假設這個函數定義如下:

function EntriesReceived(result) {
    // handle the result of the AJAX call here
}

如果你想將它作為JSON請求發送,你應該使用$ .ajax方法,它允許你指定正確的請求內容類型:

function GetEntries(firstLetter) {
    $.ajax({
        url: '/Home/GetEntries',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ firstLetter: firstLetter }),
        success: function(result) {
            // handle the result of the AJAX call here
        }
    });
}

我在控制器操作中看到的另一個問題是您將其定義為void 在ASP.NET MVC中,常見的建議約定是所有控制器操作都必須返回ActionResult類的實例。 但是如果你不想向客戶端返回任何內容,那么在這種情況下使用特定的ActionResult - EmptyResult:

[HttpPost]
public ActionResult GetEntries(string firstLetter)
{
    Debug.WriteLine(firstLetter);
    return new EmptyResult();
}

暫無
暫無

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

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