【问题标题】:How to use Data Annotations when You are submitting form using Ajax Call in MVC?在 MVC 中使用 Ajax 调用提交表单时如何使用数据注释?
【发布时间】:2019-12-24 09:21:13
【问题描述】:

我正在使用 JS 提交表单,但我想验证该表单中的一个文件,我在模型中应用了注释,但这些注释没有显示在页面上,而不是抛出异常,因为注释正在工作,但表单是由于 Ajax 调用而提交。 有人可以帮帮我吗?

<form id="share">
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="container col-md-12">
        <table id="myTable" class="cell-border compact hover">
            <thead>
                <tr>
                    <th style="text-align:center">@Html.DisplayNameFor(m => Model.tags.First().Id)</th>
                    <th style="text-align:center">@Html.DisplayNameFor(m => Model.tags.First().TagName)</th>
                    <th style="text-align:center">@Html.DisplayNameFor(m => Model.tags.First().TagCategory)</th>
                    <th style="text-align:center">@Html.DisplayNameFor(m => Model.tags.First().TagValue)</th>
                    <th style="text-align:center"> Action</th>
                </tr>
            </thead>
            <tbody>
                @for (int i = 0; i < Model.tags.Count(); i++)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(m => Model.tags[i].Id)
                            @Html.HiddenFor(m => Model.tags[i].Id)
                        </td>
                        <td>
                            @Html.DisplayFor(m => Model.tags[i].TagName)
                        </td>
                        <td>
                            @Html.DisplayFor(m => Model.tags[i].TagCategory)
                        </td>
                        <td>
                            @Html.EditorFor(m => Model.tags[i].TagValue, new { htmlAttributes = new { @id = "TagVaule_" + Model.tags[i].Id, @class = "form-control" } })
                            @Html.ValidationMessageFor(m => Model.tags[i].TagValue, "", new { @class = "text-danger" })

                        </td>
                        <td>
                            <button type="button" class="btn btn-danger" onclick="UpdateRow(@Model.tags[i].Id)">Update</button>
                        </td>
                    </tr>
                }
            </tbody>
        </table>
        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content" id="myModalContent">

                </div>
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-5 col-md-10">
                <button type="button" class="btn btn-danger" onclick="BulkUpdate()">BulkUpdate</button>
            </div>
        </div>
    </div>
</form>
@section Scripts{
    <script>
        $(document).ready(function () {
            $('#myTable').DataTable();
        });

           function BulkUpdate()
           {
               debugger;
                   var form= $("#share");
                   $.ajax({
                   type: 'GET', //GET
                   url: '@Url.Action("BulkUpdate", "Home")',
                   data: form.serialize(),
                   success: function (data) {
                       debugger;
                    $('#myModalContent').html(data);
                    $('#myModal').modal('show');
                   }
               });

            }
        //BulkUpdate Confirmation
         function BulkConfirm()
         {
             var form= $("#share");
                $.ajax({
                   type: 'POST', //GET
                   url: '@Url.Action("BulkUpdateConfirmation", "Home")',
                   data: form.serialize()
                });
                $("#myModal").modal('hide')
            }

        //Single row update
        var RowId = 0;
        var tagvalue = 0;
            function UpdateRow(id)
            {
                tagvalue = $("#TagVaule_" + id).val();
                RowId=id;
                DisplayModal();
            }

            function DisplayModal()
            {

                 $.ajax({
                    type: "GET",
                     url: '@Url.Action("Update","Home")',
                    data: {
                        id: RowId,
                        value: tagvalue
                    },
                    success: function(data)
                {
                    debugger;
                    $('#myModalContent').html(data);
                    $('#myModal').modal('show');
                }
                });

            }
            function Confirm()
            {
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("SaveUpdate","Home")',
                    data: {
                        id: RowId,
                        value: tagvalue
                    },
                });
                $("#myModal").modal('hide')
            }

    </script>
}

【问题讨论】:

    标签: javascript c# ajax model-view-controller


    【解决方案1】:
     [HttpPost]
            public ActionResult AddStudent()
            {
                var student = new Student();
    
                // The TryUpdateModel will use data annotation to validate
                // the data passed over from the client. If any validation
                // fails, the error will be written to the "ModelState".
                var valid = TryUpdateModel(student);
    
                string studentPartialViewHtml = null;
                if (valid)
                {
                    // Add the student to the repository.
                    // In any pratical application, exception handling should be used
                    // when making data access. In this small example, I will just cross
                    // my finger to say "there is no chance to encounter exeption" when
                    // adding the student. Indeed, the chance of exception is very minimal
                    // when adding students to my small repositoty. If the validation is
                    // successful, I will simply tell the client that the student is added.
                    StudentRepository.AddStudent(student);
    
                    // Obtain the html string from the partial view "Students.ascx"
                    var students = StudentRepository.GetStudent();
                    studentPartialViewHtml = RenderPartialViewToString("Students", students);
                }
    
                return Json(new {Valid = valid,
                                 Errors = GetErrorsFromModelState(), 
                    StudentsPartial = studentPartialViewHtml
                });
            }
    

    TryUpdateModel 方法接受一个学生对象。它从 Request 对象读取发送到服务器的数据,并尝试通过匹配属性名称和发布数据的名称来更新学生对象中的属性。 更新学生对象后,它会检查学生类中的数据注释以验证数据。如果发现问题,它会将错误消息添加到控制器的 ModelState 对象中。 TryUpdateModel 方法的返回类型为布尔值,表示模型是否已成功验证。

    $.ajax({
                cache: false,
                type: "POST",
                url: addStudentUrl,
                data: data,
                dataType: "json",
                success: function (data) {
                    // There is no problem with the validation
                    if (data.Valid) {
                        $("#divStudent").html(data.StudentsPartial);
                        $("input").val("");
                        return;
                    }
    
                    // Problem happend during the validation, display
                    // the messages. The following script will display the last
                    // message related to the field.
                    $.each(data.Errors, function (key, value) {
                        if (value != null) {
                            $("#Err_" + key).html(value[value.length - 1].ErrorMessage);
                        }
                    });
                },
                error: function (xhr) {
                    alert(xhr.responseText);
                    alert("Critical Error!. Failed to call the server.");
                }
            })
    

    详情可以关注link

    【讨论】:

      猜你喜欢
      • 2014-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-03
      • 2017-05-11
      • 2021-07-09
      相关资源
      最近更新 更多