动态删除ASP MVC中元素的必填属性? [英] dynamically remove an element's required attribute in ASP MVC?
问题描述
在使用无干扰验证的ASP MVC项目中,有没有办法从元素中动态删除Required属性?
Is there a way, in an ASP MVC project using unobtrusive validation, to dynamically remove the Required attribute from an element?
该元素在视图模型中装饰为Required注释.我以为我可以通过使用JQuery删除html属性"data-val-required"来删除此元素,但客户端验证仍会按需处理该元素.通过操纵不显眼的验证属性来操纵元素的验证是否不可能?
The element is decorated with a Required annotation in the view model. I thought I could remove this by removing the html attribute, "data-val-required," with JQuery but client validation still treats the element as required. Is it impossible to manipulate the element's validation by manipulating the unobtrusive validation attributes?
这是我尝试过的方法,但是没有用.如果要取消选中复选框,我想删除必填属性.
This is what I tried, but it didn't work. I wanted to remove the required attribute if a check box was unchecked.
$("#chkTempHire").click(function () {
var checked = $(this).attr("checked");
var attr = $("#txtTempHireEndDate").attr("data-val-required");
var hasAttr = false;
if (typeof attr !== typeof undefined && attr !== false)
hasAttr = true;
if (!checked && hasAttr)
$("#txtTempHireEndDate").removeAttr("data-val-required");
});
我错过了什么吗?还是不可能?
Am I missing something, or is it just not possible?
谢谢!
推荐答案
您可以使用jQuery内置的.rules()
方法,无需手动删除属性.
You can use the .rules()
method built into jQuery, you don't need to manually remove attributes.
要删除:
$("#txtTempHireEndDate").rules("remove", "required")
要添加:
$("#txtTempHireEndDate").rules("add", "required")
这篇关于动态删除ASP MVC中元素的必填属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!