【问题标题】:MVC Controller Method Parameter Always NullMVC 控制器方法参数始终为空
【发布时间】:2013-01-18 10:36:54
【问题描述】:

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

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

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

我的控制器方法断点被命中:

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 属性添加到我的控制器:

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

我尝试将参数名称更改为“id”以匹配我的路由映射:

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

【问题讨论】:

    标签: c# javascript asp.net-mvc-4


    【解决方案1】:

    以下应该可以工作

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

    【讨论】:

    • 那行得通。我非常感谢您的快速帮助。在我对这个问题的研究中,我没有看到它说要执行{ firstLetter: firstLetter } 的任何地方。也许我只是错过了。谢谢!
    • 而且,是的,像您所说的那样定义了一个 EntriesReceived() 函数。我同意不返回无效。我只是还没走到那一步。很棒的提示。非常感谢您的彻底和准确的回答。在过去的几个月里,你对我的帮助比你所知道的要多。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多