使用AJAX时,表单数据未发布到控制器

JMK*_*JMK 1 html javascript ajax jquery asp.net-mvc-4

好的,我在我看来有这个表格:

<form id="MyForm">
<input type="text" name="myinput" />
<button type="submit" />
</form>
Run Code Online (Sandbox Code Playgroud)

我在我的视图顶部有以下Javascript,它在页面加载时运行:

<script type="text/javascript">
    $(document).ready(
        function () {
            $("#MyForm").submit(
                function () {
                    var url = "Home/TestAjax";

                    var dataToSend = $("#MyForm").serialize();
                    alert(dataToSend);

                    $.ajax
                    (
                        {
                            type: "POST",
                            url: url,
                            data: dataToSend,
                            success: function (data) {
                                alert(data);
                            }
                        }
                    );

                    return false;
                }
            );
        }
    );
</script>
Run Code Online (Sandbox Code Playgroud)

正如警报框所验证的那样,表单正在被序列化为ajax.这是我的TestAjax控制器方法:

[HttpPost]
public string TestAjax(string data)
{
    return !string.IsNullOrEmpty(data) ? "Success" : "Failure";
}
Run Code Online (Sandbox Code Playgroud)

返回的值是Failure,因为AJAX没有被回发.我在这做错了什么?

谢谢

Dar*_*rov 6

输入字段的名称myinput不是data.因此,请确保您始终为行动的参数命名:

[HttpPost]
public ActionResult TestAjax(string myinput)
{
    return !string.IsNullOrEmpty(myinput) ? Content("Success") : Content("Failure");
}
Run Code Online (Sandbox Code Playgroud)

当您使用$("#MyForm").serialize()这将返回myinput=some_value这里some_value显然是用户在此输入字段中已输入的值.

如果您的表单中有2个输入字段:

<form id="MyForm">
    <input type="text" name="foo" />
    <input type="text" name="bar" />
    <button type="submit" />
</form>
Run Code Online (Sandbox Code Playgroud)

你当然会写一个视图模型:

public class MyViewModel
{
    public string Foo { get; set; }
    public string Bar { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

您的控制器操作将作为参数:

[HttpPost]
public ActionResult TestAjax(MyViewModel model)
{
    return !string.IsNullOrEmpty(model.Foo) ? Content("Success") : Content("Failure");
}
Run Code Online (Sandbox Code Playgroud)

另请注意,在ASP.NET MVC控制器中,操作应该返回ActionResults,而不是字符串或其他.

  • 我已经看了十次JS和C#代码并将HTML放在一边,但有时HTML非常重要,其余的...... +1 (2认同)