Skip to main content
 首页 » 编程设计

c#之MVC Controller 方法参数始终为空

2024年02月20日12softidea

我的 javascript 函数正在调用我的 MVC 4 Controller ,但参数始终为空。这似乎是一个常见问题,我已经尝试了一些我研究过的东西,但没有任何效果。知道为什么它总是 null 吗?

我的 javascript GetEntries() 函数正确地创建了一个显示值的警报:

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

我的 Controller 方法断点被命中:

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

但是,firstLetter 始终为空。我不确定该怎么做。

失败的尝试:

我尝试使用 JSON.stringify 发帖。

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

我尝试将 HttpPost 属性添加到我的 Controller :

[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 
        } 
    }); 
} 

我看到您的 Controller 操作的另一个问题是您将其定义为 void。在 ASP.NET MVC 中,常见的既定约定是所有 Controller 操作都必须返回 ActionResult 类的实例。但是,如果您不想向客户端返回任何内容,则在这种情况下使用特定的 ActionResult - EmptyResult:

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