当您在MVC中使用Ajax Call提交表单时,如何使用数据注释?



我正在使用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>
}
[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
});
}

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

$.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.");
}
})

有关详细信息,您可以点击此链接

最新更新