提问人:Saeid 提问时间:4/22/2012 更新时间:4/22/2012 访问量:11348
如果非显眼验证无效,则显示 div,如果在 MVC 3 中有效,则将其隐藏
show div if unobtrusive validation was invalid and hide it if Valid in MVC 3
问:
这是我的“编辑”视图的一部分:
<dt>
@Html.LabelFor(model => model.MainModel.StartDate)
</dt>
<dd>
@Html.TextBoxFor(model => model.MainModel.StartDate)
@Html.ValidationMessageFor(model => model.MainModel.StartDate)
<div class="targetDiv"> My content </div>
</dd>
因此,正如你们都知道的那样,当我的模型中的字段无效时,不显眼地显示错误消息,如果有效,则将其隐藏。现在,我想向此过程添加另一个操作。如果值为无效,我需要显示,如果值为有效,请将其隐藏。你有什么建议?StartDate
StartDate
"targetDiv" div
StartDate
答:
4赞
Mathew Thompson
4/22/2012
#1
您必须首先验证您的表单(假设它的 id 为 myForm,并且以下代码包装在保存按钮单击函数中):
$("#myForm").validate();
if ($("#myForm").valid()) {
$("#targetDiv").css("display", "none");
}
else {
if ($("[id='MainModel.StartDate']").hasClass("input-validation-error") {
//note the strange ID selector above, that's because it's got a . in :)
$("#targetDiv").css("display", "block");
}
else {
$("#targetDiv").css("display", "none");
}
}
2赞
Matija Grcic
4/22/2012
#2
不显眼的验证将 css 类添加到您的验证元素中,这就是它确定是显示还是隐藏验证消息的方式。这是一个检查:
<div class="editor-label">
<label>Start date</label>
<input class="text-box single-line" data-val="true" data-val-required="Must not be Empty" id="StartDate" name="StartDate" type="text" value="">
<span class="field-validation-valid" data-valmsg-for="StartDate" data-valmsg-replace="true"></span>
</div>
<div class="targetDiv">Your div shown only if StartDate is invalid</div>
这就是你的html在源代码中的样子。在 StartDate 输入中写入无效数据后,请注意添加到输入和 span 元素中的类,它看起来会略有不同:
<div class="editor-label">
<label>Start date</label>
<input class="text-box single-line input-validation-error" data-val="true" data-val-required="Must not be Empty" id="StartDate" name="StartDate" type="text" value="">
<span class="field-validation-error ui-state-error-icon ui-icon-alert" data-valmsg-for="StartDate" data-valmsg-replace="true"></span>
</div>
您可以检查 span 元素是否具有 field-validation-error 类并显示您的 targetDiv。 我模仿了不显眼的验证是如何工作的,并提供了工作示例:
$(function(){
$('.targetDiv').hide(); //hide your div
$('#StartDate').change(function() { //capture change event for your input StartDate
$(this).addClass('input-validation-error'); //add unobtrusive css class for not valid
$(this).next().removeClass('field-validation-valid').addClass('field-validation-error ui-state-error-icon ui-icon-alert'); //add unobtrusive css class for not valid on span
if( $(this).next().hasClass('field-validation-error')) //check if span has a error class on it
{
$('.targetDiv').show(); //show your div
}
});
});
在实际示例中,您只需要使用:
$('#StartDate').change(function() {
if( $(this).next().hasClass('field-validation-error'))
{
$('.targetDiv').show();
}
});
下面是 jsFiddle:http://jsfiddle.net/mgrcic/Zj6zS/
问候。
8赞
archil
4/22/2012
#3
可以使用 ModelState.IsValidField 方法检查字段有效性
<div class="targetDiv" @if (Html.ViewData.ModelState.IsValidField("StartDate"))
{
<text>style="display:none"</text>
}>
My content
</div>
评论