gpt4 book ai didi

javascript - 表单未发布资源未找到

转载 作者:行者123 更新时间:2023-12-03 09:42:51 25 4
gpt4 key购买 nike

我正在尝试将表单发布到 MVC Controller ,该 Controller 使用 AJAX 获取表单集合。我一直在关注这个How to pass formcollection using ajax call to an action? 。但是,当我向 Controller 发出发布请求时,它会以某种方式反转路径的顺序,例如在我的 AJAX 代码中,我的 URL 是 '/Settings/EditDatasource' 但当我发出 post 请求时,它变成 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");
}
})
});
})

这是我的 Controller :

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

return new EmptyResult();
}

最佳答案

解决方案如下。创建一个简单的 POST 操作

[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>

输出将是 -

enter image description here

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

关于javascript - 表单未发布资源未找到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31134555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com