我实现了远程验证。它适用于正常的字段,但如果字段位于kendowindow jquery验证不起作用。
我该如何解决这个问题?
答案 0 :(得分:3)
这可以使用Kendo UI验证器来实现,如下所示:
具有“远程”注释属性的模型:
public class ProductViewModel
{
[Editable(false)]
public int ProductID { get; set; }
[Required]
[Remote("UniqueName", "Home", ErrorMessage = "The entered name already exists.")]
public string ProductName { get; set; }
}
具有“UniqueName”的控制器操作:
public ActionResult UniqueName(string productName)
{
var context = new NorthwindEntities();
return Json(!context.Products.Any(p => p.ProductName == productName), JsonRequestBehavior.AllowGet);
}
将自定义验证规则添加到“远程”验证属性的Kendo UI验证规则的脚本(可以在网格初始化代码之前放置在页面的任何位置):
<script>
(function ($, kendo) {
$.extend(true, kendo.ui.validator, {
rules: {
//define custom validation rule to match remote validation:
mvcremotevalidation: function (input) {
if (input.is("[data-val-remote]") && input.val() != "") {
var remoteURL = input.attr("data-val-remote-url");
var valid;
$.ajax({
async: false,
url: remoteURL,
type: "GET",
dataType: "json",
data: validationData(input, this.element),
success: function (result) {
valid = result;
},
error: function () {
valid = false;
}
});
return valid;
}
return true;
}
},
messages: {
mvcremotevalidation: function (input) {
return input.attr("data-val-remote");
}
}
});
function validationData(input, context) {
var fields = input.attr("data-val-remote-additionalFields").split(",");
var name = input.prop("name");
var prefix = name.substr(0, name.lastIndexOf(".") + 1);
var fieldName;
var data = {};
for (var i = 0; i < fields.length; i++) {
fieldName = fields[i].replace("*.", prefix);
data[fieldName] = $("[name='" + fieldName + "']", context).val();
}
return data;
}
})(jQuery, kendo);
</script>
网格初始化代码:
@(Html.Kendo().Grid<KendoUIMVC5.Models.ProductViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Command(comm =>
{
comm.Edit();
});
columns.Bound(p => p.ProductID);
columns.Bound(p => p.ProductName);
})
.Pageable()
.Sortable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(p => p.ProductID);
})
.Read(read => read.Action("Read", "Home"))
.Update(update => update.Action("Update", "Home"))
)
)