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

标签 c# jquery asp.net asp.net-mvc asp.net-ajax

我有一个弹出表单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/

相关文章:

c# - 为Windows 8应用选择哪种语言(含义是什么)?

c# - 使用 rest api 从 Web 应用程序将文件上传到 Azure 文件存储

c# - 将消息从类后面的代码返回到 Jquery

javascript - jQuery `index()` 在 Vanilla JS 中等效

jquery - 使用 jQuery 和 JSON 时如何让我的文本区域保留换行符?

jquery - 使用jquery和webmethod在Gridview中延迟加载

c# - Xml 序列化 - 忽略父节点

c# - 无法在 Entity Framework 中获取导航属性

c# - RhinoETL - 加入两个表作为输入,在输出时写入两个表

c# - 标记在 XML 命名空间中不存在