gpt4 book ai didi

c# - 来自弹出表单的 ajax 数据发布未命中 Controller 方法 ASP.NET MVC

转载 作者:行者123 更新时间:2023-12-01 01:40:08 24 4
gpt4 key购买 nike

我有一个弹出表单AddorEdit.cshtml,它是从index.cshtml页面调用的。表单正在打开,但无法将数据发送到 Controller 方法。

索引页

// index.cshtml //
<a class="btn btn-success" style="margin-bottom:10px;" onclick="PopupForm('@Url.Action("AddorEdit", "Vehicles")')"><i class="fa fa-plus"></i> Add New</a>
<table id="tbl_vehicle" class="table table-striped table-bordered" style="width:100%;" >
//table block
<script>
function SubmitForm(form) {
$.ajax({
type: "POST",
url: form.action,
data: $(form).serialize(),
success: function (date) {
if(data.success)
{
Popup.dialog('close');
dataTable.ajax.reload();
}
}
});
</script>

弹出表单

//AddorEdit.cshtml //

@using (Html.BeginForm("AddorEdit", "Vehicles", FormMethod.Post, new { onsubmit = "return SubmitForm(this)" }))
//form

Controller 方法

// VehiclesController.cs //

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddorEdit([Bind(Include = "Id,VehicleType,Amount,RenewPeriod,Status")] Vehicle vehicle)
{

if (ModelState.IsValid)
{
if (vehicle.Id <= 0)
{
vehicle.RegisteredDate = DateTime.Now;
vehicle.RegisteredBy = "admin";
db.Vehicle.Add(vehicle);
}
else
{
db.Entry(vehicle).State = EntityState.Modified;
}

db.SaveChanges();
}
return Json(new { success = true, message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);

}

我无法检测为什么数据没有发布到 Controller 方法。谢谢!!!

最佳答案

use like this in your Form,it will fix your problem

@using (Html.BeginForm("AddorEdit", "Vehicles", FormMethod.Post, new { onsubmit =
"return SubmitForm(this)" }))
{
@Html.AntiForgeryToken()
}

如果您正在使用

[ValidateAntiForgeryToken]

此属性位于操作方法之上你必须使用

@Html.AntiForgeryToken()

在你看来

关于c# - 来自弹出表单的 ajax 数据发布未命中 Controller 方法 ASP.NET MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59692582/

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