重新初始化不显眼的 jquery 验证
Reinitialize unobstrusive jquery validation
我通过 ajax 重新绑定了视图模型,因为我不喜欢默认的功能模式弹出窗口,因为我忘记了我正在关注哪个教程 link,这是我的一些代码
数据表代码
$(document).ready(function () {
$("#btnNew").text("New");
$('#grid-src').hide();
$('#btnToggleSrc').click(function () {
$('#grid-src').toggle();
});
$("#btnNew").on("click", function (e) {
$.ajax({
type: "POST",
url: '@Url.Action("Edit", "Roles", new { area = "PM" })',
dataType: 'json',
data: { id: 0 },
success: function (obj) {
switch (obj.ResponseMsg.MsgType) {
case 'SUCCESS':
var roles = obj.Data;
$.ajax({
type: "POST",
url: '@Url.Action("LoadEdit", "Roles", new { area = "PM" })',
dataType: 'json',
data: { role: roles },
sucecss: function (obj) {
},
complete: function () {
$('#modal-title').text('New Role');
$('#edit-form').modal('show');
}
});
break;
case 'WARNING':
toastr.warning(obj.ResponseMsg.MsgDesc);
break;
case 'ERROR':
toastr.error(obj.ResponseMsg.MsgDesc);
break;
}
}
});
});
$('#table-container').on('click', 'a.btn-edit', function (e) {
var param = parseInt(this.id.replace('edit-', ''));
$.post('@Url.Action("Edit", "Roles", new { area = "PM" })', { id: param })
.done(function (obj) {
switch (obj.ResponseMsg.MsgType) {
case 'SUCCESS':
var role = obj.Data;
$.post('@Url.Action("LoadEdit", "Roles", new { area = "PM" })', { role: role })
.done(function (obj) {
debugger;
$('#edit-form-partial').html(obj);
//$.validator = $('#frmSubmit').validate(
//{
// ignore: ":hidden"
//});
$('#modal-title').text('Edit Role');
$('#edit-form').modal('show');
});
break;
case 'WARNING':
toastr.warning(obj.ResponseMsg.MsgDesc);
break;
case 'ERROR':
toastr.error(obj.ResponseMsg.MsgDesc);
break;
}
});
});
var url = "@Url.Action("Read", "Roles", new { area = "PM" })"
var oTable = $('#table').dataTable({
"processing": false,
"serverSide": true,
"orderMulti": false,
"sScrollY": ($(window).height() - 300),
"sScrollYInner": "100%",
"sheight": "425px",
"pageLength": 10,
"dom": '<"top"i>rt<"bottom"lp><"clear">',
"ajax": {
"url": url,
"type": "POST",
"datatype": "json",
"error": function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
},
"columns": [
{ "data": "ID", "name": "ID", "autowidth": true, "visible": false },
{ "data": "RoleName", "name": "RoleName", "autowidth": true },
{ "data": "CreatedBy", "name": "CreatedBy", "autowidth": true, "sorting": false },
{
"data": "CreatedTime", "name": "CreatedTime", "autowidth": true, "render": function (jsonDate) {
return generateDate(jsonDate);
},
"sorting": false
},
{ "data": "ModifiedBy", "name": "ModifiedBy", "autowidth": true, "sorting": false },
{
"data": "ModifiedTime", "name": "ModifiedTime", "autowidth": true, "render": function (jsonDate) {
return generateDate(jsonDate);
},
"sorting": false
},
{
"data": "ID", "width": "50px", "render": function (data) {
return '<a class="btn-edit" href="javascript:void(0)" id="edit-' + data + '" style="cursor: pointer">Edit</a>';
},
"sorting": false
},
{
"data": "ID", "width": "50px", "render": function (data) {
return '<a class="btn-delete" href="javascript:void(0) id="delete-' + data + '" style="cursor: pointer">Delete</a>';
},
"sorting": false
}
]
});
部分编辑表格
@myProject.MyViewModel
@{
Html.EnableClientValidation(true);
}
@using (Ajax.BeginForm("Save", "Roles", new { area = "PM" }, new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
OnSuccess = "successSave",
OnFailure = "failSave"
},
new { @id = "frmSubmit" }))
{
@Html.AntiForgeryToken()
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"><span id="modal-title"></span></h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-4">
@Html.HiddenFor(model => model.ID, new { @id = "roleFlag" })
@Html.LabelFor(model => model.RoleName)
</div>
<div class="col-8">
@Html.TextBoxFor(model => model.RoleName, new { @style = "width:210px", @id = "tbRoleName", @class = "form-control" })
@Html.ValidationMessageFor(model => model.RoleName, "", new { @class = "text-danger", style = "font-size: 12px;", @id = "val-role" })
</div>
</div>
</div>
<div class="modal-footer">
<div class="row right">
<div class="col-2">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</div>
}
和控制器代码
[HttpPost]
public ActionResult Edit (long id)
{
var result = new JsonResult();
try
{
BPPMRoles objBP = new BPPMRoles();
var role = objBP.Find(id);
if (objBP.MsgCode != 0)
{
result = new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
ResponseMsg = new
{
MsgCode = objBP.MsgCode,
MsgType = "ERROR",
MsgDesc = "There's something wrong, please contact us about this issue (Error Code = " + objBP.MsgCode + ")"
},
Data = new myViewModel()
}
};
return result;
}
var mapper = mapConfig.CreateMapper();
var roles = mapper.Map<myModel, myViewMode>(role);
result = new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
ResponseMsg = new
{
MsgCode = 0,
MsgType = "SUCCESS",
MsgDesc = string.Empty
},
Data = roles ?? new myViewModel()
}
};
return result;
}
catch (Exception err)
{
result = new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
ResponseMsg = new
{
MsgCode = 10,
MsgType = "ERROR",
MsgDesc = "There's something wrong, please contact us about this issue (Error Code = " + 10 + ")"
},
Data = new myViewModel()
}
};
return result;
}
}
[HttpPost]
public ActionResult LoadEdit(myViewModel role)
{
return PartialView("_Edit", role);
}
视图模型
public class myViewModel
{
public long ID { get; set; }
[Display(Name = "Role")]
[Required(ErrorMessage = "Role must not be empty!", AllowEmptyStrings = false)]
[MaxLength(150)]
public string RoleName { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedTime { get; set; }
public string ModifiedBy { get; set; }
public DateTime? ModifiedTime { get; set; }
}
问题是,重新绑定部分视图后,强制验证始终为真,重新绑定后所需的验证不起作用
编辑:我试过 .validate() 和 .valid()
始终returns为真,即使文本框为空
我的一个项目加载了 json 数据并用它填充了多个表单。
方式一
我设法通过做 3 件事让它工作。
1- 在填充字段之前重置表单,如下所示:
$("#MyFormId").trigger("reset");
2- 使用 javascript
填充字段
$("#MyFieldName").val(myValueGoesHere);
3- 在所有文本字段上触发更改事件,如下所示:
$("#MyFieldName").trigger("change");
注意 2 和 3 可以像这样在一行中实现:
$("#MyFieldName").val(myValueGoesHere).trigger("change");
方式二
如果您确实需要动态加载表单的 "html content" 而不仅仅是数据...
你可以试试这个:
function rebindvalidators() {
var $form = $("#MyFormId");
$form.unbind();
$form.data("validator", null);
$.validator.unobtrusive.parse($form);
$form.validate($form.data("unobtrusiveValidation").options);
}
像这样从完成的处理程序中调用该函数:
.done(function (obj) {
debugger;
$('#edit-form-partial').html(obj);
rebindvalidators();//rebind your validators after loading the html.
//$.validator = $('#frmSubmit').validate(
//{
// ignore: ":hidden"
//});
$('#modal-title').text('Edit Role');
$('#edit-form').modal('show');
});
我通过 ajax 重新绑定了视图模型,因为我不喜欢默认的功能模式弹出窗口,因为我忘记了我正在关注哪个教程 link,这是我的一些代码
数据表代码
$(document).ready(function () {
$("#btnNew").text("New");
$('#grid-src').hide();
$('#btnToggleSrc').click(function () {
$('#grid-src').toggle();
});
$("#btnNew").on("click", function (e) {
$.ajax({
type: "POST",
url: '@Url.Action("Edit", "Roles", new { area = "PM" })',
dataType: 'json',
data: { id: 0 },
success: function (obj) {
switch (obj.ResponseMsg.MsgType) {
case 'SUCCESS':
var roles = obj.Data;
$.ajax({
type: "POST",
url: '@Url.Action("LoadEdit", "Roles", new { area = "PM" })',
dataType: 'json',
data: { role: roles },
sucecss: function (obj) {
},
complete: function () {
$('#modal-title').text('New Role');
$('#edit-form').modal('show');
}
});
break;
case 'WARNING':
toastr.warning(obj.ResponseMsg.MsgDesc);
break;
case 'ERROR':
toastr.error(obj.ResponseMsg.MsgDesc);
break;
}
}
});
});
$('#table-container').on('click', 'a.btn-edit', function (e) {
var param = parseInt(this.id.replace('edit-', ''));
$.post('@Url.Action("Edit", "Roles", new { area = "PM" })', { id: param })
.done(function (obj) {
switch (obj.ResponseMsg.MsgType) {
case 'SUCCESS':
var role = obj.Data;
$.post('@Url.Action("LoadEdit", "Roles", new { area = "PM" })', { role: role })
.done(function (obj) {
debugger;
$('#edit-form-partial').html(obj);
//$.validator = $('#frmSubmit').validate(
//{
// ignore: ":hidden"
//});
$('#modal-title').text('Edit Role');
$('#edit-form').modal('show');
});
break;
case 'WARNING':
toastr.warning(obj.ResponseMsg.MsgDesc);
break;
case 'ERROR':
toastr.error(obj.ResponseMsg.MsgDesc);
break;
}
});
});
var url = "@Url.Action("Read", "Roles", new { area = "PM" })"
var oTable = $('#table').dataTable({
"processing": false,
"serverSide": true,
"orderMulti": false,
"sScrollY": ($(window).height() - 300),
"sScrollYInner": "100%",
"sheight": "425px",
"pageLength": 10,
"dom": '<"top"i>rt<"bottom"lp><"clear">',
"ajax": {
"url": url,
"type": "POST",
"datatype": "json",
"error": function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
},
"columns": [
{ "data": "ID", "name": "ID", "autowidth": true, "visible": false },
{ "data": "RoleName", "name": "RoleName", "autowidth": true },
{ "data": "CreatedBy", "name": "CreatedBy", "autowidth": true, "sorting": false },
{
"data": "CreatedTime", "name": "CreatedTime", "autowidth": true, "render": function (jsonDate) {
return generateDate(jsonDate);
},
"sorting": false
},
{ "data": "ModifiedBy", "name": "ModifiedBy", "autowidth": true, "sorting": false },
{
"data": "ModifiedTime", "name": "ModifiedTime", "autowidth": true, "render": function (jsonDate) {
return generateDate(jsonDate);
},
"sorting": false
},
{
"data": "ID", "width": "50px", "render": function (data) {
return '<a class="btn-edit" href="javascript:void(0)" id="edit-' + data + '" style="cursor: pointer">Edit</a>';
},
"sorting": false
},
{
"data": "ID", "width": "50px", "render": function (data) {
return '<a class="btn-delete" href="javascript:void(0) id="delete-' + data + '" style="cursor: pointer">Delete</a>';
},
"sorting": false
}
]
});
部分编辑表格
@myProject.MyViewModel
@{
Html.EnableClientValidation(true);
}
@using (Ajax.BeginForm("Save", "Roles", new { area = "PM" }, new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
OnSuccess = "successSave",
OnFailure = "failSave"
},
new { @id = "frmSubmit" }))
{
@Html.AntiForgeryToken()
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"><span id="modal-title"></span></h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-4">
@Html.HiddenFor(model => model.ID, new { @id = "roleFlag" })
@Html.LabelFor(model => model.RoleName)
</div>
<div class="col-8">
@Html.TextBoxFor(model => model.RoleName, new { @style = "width:210px", @id = "tbRoleName", @class = "form-control" })
@Html.ValidationMessageFor(model => model.RoleName, "", new { @class = "text-danger", style = "font-size: 12px;", @id = "val-role" })
</div>
</div>
</div>
<div class="modal-footer">
<div class="row right">
<div class="col-2">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</div>
}
和控制器代码
[HttpPost]
public ActionResult Edit (long id)
{
var result = new JsonResult();
try
{
BPPMRoles objBP = new BPPMRoles();
var role = objBP.Find(id);
if (objBP.MsgCode != 0)
{
result = new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
ResponseMsg = new
{
MsgCode = objBP.MsgCode,
MsgType = "ERROR",
MsgDesc = "There's something wrong, please contact us about this issue (Error Code = " + objBP.MsgCode + ")"
},
Data = new myViewModel()
}
};
return result;
}
var mapper = mapConfig.CreateMapper();
var roles = mapper.Map<myModel, myViewMode>(role);
result = new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
ResponseMsg = new
{
MsgCode = 0,
MsgType = "SUCCESS",
MsgDesc = string.Empty
},
Data = roles ?? new myViewModel()
}
};
return result;
}
catch (Exception err)
{
result = new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
ResponseMsg = new
{
MsgCode = 10,
MsgType = "ERROR",
MsgDesc = "There's something wrong, please contact us about this issue (Error Code = " + 10 + ")"
},
Data = new myViewModel()
}
};
return result;
}
}
[HttpPost]
public ActionResult LoadEdit(myViewModel role)
{
return PartialView("_Edit", role);
}
视图模型
public class myViewModel
{
public long ID { get; set; }
[Display(Name = "Role")]
[Required(ErrorMessage = "Role must not be empty!", AllowEmptyStrings = false)]
[MaxLength(150)]
public string RoleName { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedTime { get; set; }
public string ModifiedBy { get; set; }
public DateTime? ModifiedTime { get; set; }
}
问题是,重新绑定部分视图后,强制验证始终为真,重新绑定后所需的验证不起作用
编辑:我试过 .validate() 和 .valid()
始终returns为真,即使文本框为空
我的一个项目加载了 json 数据并用它填充了多个表单。
方式一 我设法通过做 3 件事让它工作。
1- 在填充字段之前重置表单,如下所示:
$("#MyFormId").trigger("reset");
2- 使用 javascript
填充字段 $("#MyFieldName").val(myValueGoesHere);
3- 在所有文本字段上触发更改事件,如下所示:
$("#MyFieldName").trigger("change");
注意 2 和 3 可以像这样在一行中实现:
$("#MyFieldName").val(myValueGoesHere).trigger("change");
方式二
如果您确实需要动态加载表单的 "html content" 而不仅仅是数据...
你可以试试这个:
function rebindvalidators() {
var $form = $("#MyFormId");
$form.unbind();
$form.data("validator", null);
$.validator.unobtrusive.parse($form);
$form.validate($form.data("unobtrusiveValidation").options);
}
像这样从完成的处理程序中调用该函数:
.done(function (obj) {
debugger;
$('#edit-form-partial').html(obj);
rebindvalidators();//rebind your validators after loading the html.
//$.validator = $('#frmSubmit').validate(
//{
// ignore: ":hidden"
//});
$('#modal-title').text('Edit Role');
$('#edit-form').modal('show');
});