如何在ASP.NET MVC中使用ajax提交表单并在按钮点击后验证调用表单提交事件?

3
我正在使用asp.net mvc开发应用程序。 我正在为准备调查问题和答案的屏幕而不是做一个屏幕。 主屏幕上有一个问题表。 当我按下“添加新问题”按钮时,我使用jquery打开一个弹出窗口,并在此问题中添加问题和答案选项(“弹出窗口独立于主屏幕,即Layout = null”)。 然后,当按下此弹出窗口的“提交”按钮时,我在addOrEdit.cshtml中使用javascrit验证弹出窗口中的表单。 如果验证成功,我的目标是将asp.net mvc的表单提交事件提交给主页面上的javascript函数。 我无法做到这一点。 我在哪里犯了错误。 问题在哪里。 我尝试以解释性的方式来解释它。 我还添加了截图和代码。

Index.cshtml

@{
  ViewBag.Title = "Soru Listesi";
}

   <h2>Add Question</h2>
   <a class="btn btn-success" style="margin-bottom: 10px" onclick="PopupForm('@Url.Action("AddOrEdit","Question")')"><i class="fa fa-plus"></i> Add New Question</a>  

//table heree

Index.cshtml sectionscript

@section Scripts{
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>

<script>
   //datatable script hereee.....

function PopupForm(url) {
    var formDiv = $('<div/>');
     $.get(url)
       .done(function (response) {
         formDiv.html(response);
          Popup = formDiv.dialog({
             autoOpen: true,
             resizable: true,
              title: 'Soru Detay',
              modal: true,
              height: 'auto',
              width: '700',
              close: function () {
                 Popup.dialog('destroy').remove();
             }
       });
   });
}


function SubmitForm(form) {
   alert('gel babanaaa');
    if ($(form).valid()) {
    alert('validd');
       $.ajax({
            type: "POST",
            url: form.action,
            data: $(form).serialize(),
            success: function (data) {
                if (data.success) {
                  Popup.dialog('close');
                  dataTable.ajax.reload();
                  $.notify(data.message,
                     {
                       globalPosition: "top center",
                       className: "success",
                       showAnimation: "slideDown",
                       showDuration: 500,
                       gap: 1000
                     });
                  }
               }
          });
     }
 }
  </script>
}

AddOrEdit.cshtml

@model MerinosSurvey.Models.Questions
@{
    Layout = null;
}
@using (Html.BeginForm("AddOrEdit", "Question", FormMethod.Post, new { @class = "needs-validation", novalidate = "true", onsubmit = "return SubmitForm(this)", onreset = "return ResetForm(this)", id = "questionForm" }))
 {
// other component heree   

<div class="form-group row">
    <input type="button" value="Submit" class="btn btn-primary" id="btnSubmit" />
    <input type="reset" value="Reset" class="btn btn-secondary" />
</div>

}

AddOrEdit.cshtml脚本

<script>
 //some scriptt for validationn...

$("#btnSubmit").click(function (event) {
    var form = $("#questionForm");
    if (form[0].checkValidity() === false) {
        event.preventDefault();
        event.stopPropagation();
    }
    form.addClass('was-validated');
    // Perform ajax submit here...
    if ($(form).valid()) {       
        form[0].submitEvent();//MY PROBLEM!!!!!
    }
});

</script>

在 ASP.NET MVC 中,我希望在按钮点击和验证后调用 SubmitForm 事件。我使用了 form[0].submitEvent();,所以无法通过 AJAX 发送请求,但它并没有起作用。

img1 img2 img3

1个回答

2
替换您的Index.cshtml文件为以下代码。
   @{
        ViewBag.Title = "Soru Listesi";
    }

    <h2>Add Question</h2>
    <a class="btn btn-success" style="margin-bottom: 10px" onclick="PopupForm('@Url.Action("AddOrEdit","Question")')"><i class="fa fa-plus"></i> Add New Question</a>
    <table id="questionTable" class="table table-striped table-bordered accent-blue" style="width: 100%">
        <thead>
            <tr>
                <th>Soru No</th>
                <th>Soru Adı</th>
                <th>Oluşturma Tarihi</th>
                <th>Güncelleme Tarihi</th>
                <th>Detay/Güncelle/Sil</th>
            </tr>
        </thead>
    </table>

    <link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
    <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />



    @section Scripts{

        <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
        <script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
        <script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
        <script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
        <script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>

        <script>
            var Popup, dataTable;
            $(document).ready(function () {
                dataTable = $("#questionTable").DataTable({
                    "ajax": {
                        "url": "/Question/GetData",
                        "type": "GET",
                        "datatype": "json"
                    },
                    "columnDefs": [
                        { width: '10%', targets: 5 }
                    ],
                    "scrollX": true,
                    "scrollY": "auto",
                    "columns": [
                        { "data": "QuestionId" },
                        { "data": "QuestionName" },
                        {
                            "data": "CreatedDate",
                            "render": function (data) { return getDateString(data); }
                        },
                        {
                            "data": "UpdatedDate",
                            "render": function (data) { return getDateString(data); }
                        },
                        {
                            "data": "QuestionId",
                            "render": function (data) {
                                return "<a class='btn btn-primary btn-sm' onclick=PopupForm('@Url.Action("AddOrEdit", "Question")/" +
                                    data +
                                    "')><i class='fa fa-pencil'></i> Güncelle</a><a class='btn btn-danger btn-sm' style='margin-left:5px' onclick=Delete(" +
                                    data +
                                    ")><i class='fa fa-trash'></i> Sil</a>";
                            },
                            "orderable": false,
                            "searchable": false,
                            "width": "150px"
                        }
                    ],
                    "language": {
                        "emptyTable":
                            "Soru bulunamadı, lütfen <b>Yeni Soru Oluştur</b> butonuna tıklayarak yeni anket oluşturunuz. "
                    }
                });
            });


            function getDateString(date) {
                var dateObj = new Date(parseInt(date.substr(6)));
                let year = dateObj.getFullYear();
                let month = (1 + dateObj.getMonth()).toString().padStart(2, '0');
                let day = dateObj.getDate().toString().padStart(2, '0');
                return day + '/' + month + '/' + year;
            };


            function PopupForm(url) {
                var formDiv = $('<div/>');
                $.get(url)
                    .done(function (response) {
                        formDiv.html(response);
                        Popup = formDiv.dialog({
                            autoOpen: true,
                            resizable: true,
                            title: 'Soru Detay',
                            modal: true,
                            height: 'auto',
                            width: '700',
                            close: function () {
                                Popup.dialog('destroy').remove();
                            }

                        });
                    });
            }

            function SubmitForm(form) {
                alert('Submit Formm');
                if (form[0].checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.addClass('was-validated');

                if ($(form).valid()) {
                    alert('ben burdyaım');
                }
            }


            function ResetForm(form) {
                Popup.dialog('close');
                return false;
            }

            function Delete(id) {
                if (confirm('Bu soruyu silmek istediğinizden emin misiniz?')) {
                    $.ajax({
                        type: "POST",
                        url: '@Url.Action("Delete", "Question")/' + id,
                        success: function (data) {
                            if (data.success) {
                                dataTable.ajax.reload();
                                $.notify(data.message,
                                    {
                                        className: "success",
                                        globalPosition: "top center",
                                        title: "BAŞARILI"
                                    })
                            }
                        }

                    });
                }
            }


        </script>
    }

替换您的AddOrEdit.cshtml为下面的代码。
@model MerinosSurvey.Models.Questions
@{
  Layout = null;
}

@using (Html.BeginForm("AddOrEdit", "Question", FormMethod.Post, new { @class = "needs-validation", novalidate = "true", onsubmit = "return SubmitForm(this)", onreset = "return ResetForm(this)", id = "questionForm" }))
    {
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group row">
            @Html.LabelFor(model => model.QuestionId, new { @class = "col-form-label col-md-3" })
            <div class="col-md-9">
                @Html.TextBoxFor(model => model.QuestionId, new { @readonly = "readonly", @class = "form-control" })

            </div>
        </div>
        <div class="form-group row">
            @Html.LabelFor(model => model.QuestionName, new { @class = "col-form-label col-md-3" })
            <div class="col-md-9">
                @Html.EditorFor(model => model.QuestionName, new { htmlAttributes = new { @class = "form-control", required = "true" } })
                <div class="valid-feedback"><i class="fa fa-check">Süpersin</i></div>
                <div class="invalid-feedback "><i class="fa fa-times"></i></div>
            </div>
        </div>
        <div class="form-group row">
                @Html.LabelFor(model => model.CreatedDate, new { @class = "form-control-label col-md-3"})
                <div class="col-md-9">
                    @Html.EditorFor(model => model.CreatedDate, "{0:yyyy-MM-dd}", new { htmlAttributes = new { @class = "form-control", type = "date", @readonly = "readonly",required="false" } })

                </div>
            </div>

        <div class="form-group row ">
            <label class="col-sm-3 col-form-label">Options</label>
            <div class="col-sm-9 input-group">
                <input type="text" class="form-control" name="option[]" required placeholder="Seçenek giriniz" />
                <div class="input-group-append">
                    <button type="button" class="btn btn-success addButton"><i class="fa fa-plus"></i></button>
                </div>
            </div>
        </div>

        <!-- The option field template containing an option field and a Remove button -->
        <div class="form-group d-none row" id="optionTemplate">
            <div class="offset-sm-3 col-sm-9 input-group">
                <input class="form-control" type="text" name="option[]" required placeholder="Diğer seçenek giriniz." />
                <div class="input-group-append">
                    <button type="button" class="btn btn-danger removeButton"><i class="fa fa-times"></i></button>
                </div>
            </div>
        </div>

        <div class="form-group row">
            <input type="button" value="Submit" class="btn btn-primary" id="btnSubmit" />
            <input type="reset" value="Reset" class="btn btn-secondary" />
        </div>
    }
    <script>
        $(document).ready(function () {
            // The maximum number of options
            var MAX_OPTIONS = 5;
            $('#questionForm').on('click', '.addButton', function () {
                var $template = $('#optionTemplate'),
                    $clone = $template
                        .clone()
                        .removeClass('d-none')
                        .removeAttr('id')
                        .insertBefore($template),
                    $option = $clone.find('[name="option[]"]');

                // Add new field
                $('#questionForm').bootstrapValidator('addField', $option);
            })

                // Remove button click handler
                .on('click', '.removeButton', function () {
                    var $row = $(this).parents('.form-group'),
                        $option = $row.find('[name="option[]"]');

                    // Remove element containing the option
                    $row.remove();

                    // Remove field
                    $('#questionForm').bootstrapValidator('removeField', $option);
                })

                // Called after adding new field
                .on('added.field.bv', function (e, data) {
                    // data.field   --> The field name
                    // data.element --> The new field element
                    // data.options --> The new field options

                    if (data.field === 'option[]') {
                        if ($('#questionForm').find(':visible[name="option[]"]').length >= MAX_OPTIONS) {
                            $('#questionForm').find('.addButton').attr('disabled', 'disabled');
                        }
                    }
                })

                // Called after removing the field
                .on('removed.field.bv', function (e, data) {
                    if (data.field === 'option[]') {
                        if ($('#questionForm').find(':visible[name="option[]"]').length < MAX_OPTIONS) {
                            $('#questionForm').find('.addButton').removeAttr('disabled');
                        }
                    }
                });
        });



        $("#btnSubmit").click(function (event) {
            var form = $("#questionForm");
            if (form[0].checkValidity() === false) {
                event.preventDefault();
                event.stopPropagation();
            }

            form.addClass('was-validated');

            SubmitForm(form);

        });

    </script>

按钮点击函数在AddOrEdit.cshtml中。AddOrEdit.cshtml是一个弹出窗口。我的目标是在主布局(Index.cshtml)中提交弹出窗口并使用ajax调用,在那里重新加载数据表格(Index.cshtml)。 - user6172721
我明白,你的问题是尝试上面的脚本将会起作用,如果出现任何问题,请发送发生的错误。 - MarcosApps
子页面如何调用父页面的函数?使用submitHandler是否可行?在这种情况下,我的submitHandler是submitHandler:function(f){SubmitForm(form)} - user6172721
好的,我会准备一个项目并进行修复,发送后请记得将答案标记为“已确认”。 - MarcosApps
1
Markos,你准备了一个小项目吗?我非常担心我无法解决这个问题。同时,我正在动态创建弹出式问题的选项。我在SQL Server中维护这些选项的表格。当然,这些选项字段应该有更新和删除选项。为此,我需要像添加或编辑页面一样指定问题模型。建议你需要什么。我需要保留这些选项的ID和文本。 - user6172721
显示剩余16条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接