繁体   English   中英

表单未发布资源未找到

[英]Form not posting resource not found

我正在尝试将一个表单发布到使用AJAX进行表单收集的MVC控制器中。 我一直在关注如何使用ajax调用传递动作的formcollection? 但是,当我向控制器发出发布请求时,它以某种方式颠倒了路径的顺序,例如,在我的AJAX代码中,我的URL是'/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();
    }

解决方案如下。 创建一个简单的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>

输出将是-

在此处输入图片说明

注意:如果您不使用@Html.AntiForgeryToken() ,则ValidateAntiForgeryToken将引发错误。 因此,您AntiForgeryToken在JQuery AJAX Post中显式传递AntiForgeryToken

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM