表格未找到未找到的资源

时间:2015-06-30 09:32:25

标签: javascript jquery html ajax asp.net-mvc-5

我正在尝试将表单发布到MVC控制器,该控制器使用AJAX进行表单集合。我一直关注这个How to pass formcollection using ajax call to an action?。然而,当我向控制器发出post请求时,它以某种方式反转了路径的顺序,例如在我的AJAX代码中,我的网址为'/Settings/EditDatasource',但当我发布帖子请求时,它会变为http://localhost:53658/EditDatasource/Settings

这是我的AJAX代码

$(document).ready(function () {
    $('#postEditDatasource').click(function (event) {
        alert(JSON.stringify(deletedDatapoints));
        //serialise and assign json data to hidden field
        $('#dsDeletedDP').val(JSON.stringify(deletedDatapoints));

        //anti forgery token
        //get the form
        var form = $('#__dsAjaxAntiForgeryForm');
        //from the form get the antiforgerytoken
        var token = $('input[name="__RequestVerificationToken"]', form).val();

        var URL = 'Web/Settings/EditDatasource';

        //we make an ajax call to the controller on click
        //because the controller has a AntiForgeryToken attribute
        //we need to get the token from the form and pass it with the ajax call.
        $.ajax({
            url: URL + form.serialize(),
            data: {
                __RequestVerificationToken: token,
            },
            type: 'POST',
            success: function (result) {
                if (data.result == "Error") {
                    ShowDatasourcePostAlert('failPost', 3000);
                } else {
                    ShowDatasourcePostAlert('successPost', 3000);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert("An error has occurred please contact admin");
            }
        })
    });
})

这是我的控制器:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult EditDatasource(FormCollection collection)
    {

        return new EmptyResult();
    }

1 个答案:

答案 0 :(得分:1)

以下是解决方案。创建一个简单的POST Action

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult MyIndex(FormCollection collection)
{
    var fname = collection["FirstName"];
    var lname = collection["LastName"];
    return Json(true);
}

让你的HTML成为 -

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "MyForm" }))
{
    @Html.AntiForgeryToken()
    @Html.TextBox("FirstName","Rami")
    <input type="text" name="LastName" id="LastName" />
}

<input type="button" value="Click" id="btnSub" />

<script type="text/javascript">
    $('#btnSub').click(function () {        
        var form = $('#MyForm');
        console.log(form);
        $.ajax({
            url: '/Home/MyIndex/',
            type: 'POST',
            data: form.serialize(),
            success: function (result) {
                alert(result);
            }
        });
        return false;
    });
</script>

输出将是 -

pic10

注意: 如果您不使用@Html.AntiForgeryToken(),那么ValidateAntiForgeryToken会向您提出错误。因此,您无需在JQuery AJAX Post中明确传递AntiForgeryToken