chr*_*ris 5 jquery attributes unobtrusive-validation asp.net-mvc-3
更新:我要问的是,是否可以删除在我的viewmodel中的字段上的属性推断出的验证规则,仅在客户端.
-
当从下拉列表中进行选择时,我正在切换某些字段的显示.我还需要切换验证.
ViewModel.cs:
public int ddlTypeID { get; set; }
public Dictionary<int, string> ddlTypes { get; set; }
[Required(ErrorMessageResourceName = "msgRequired",
ErrorMessageResourceType = typeof(Resources.Globals))]
public DateTime firstDate {get; set;}
[Required(ErrorMessageResourceName = "msgRequired",
ErrorMessageResourceType = typeof(Resources.Globals))]
public DateTime otherDate {get; set;}
Run Code Online (Sandbox Code Playgroud)
Create.cshtml:
<script type="text/javascript">
$(document).ready(function () {
$('.optional').hide();
$('#ddlTypeID').change(function () {
var id = $(this).val();
if (id == 1) {
$('.optional').show();
} else {
$('.optional').hide();
}
});
});
</script>
@using (Html.BeginForm())
{
<div class="editor-field">
@Html.DropDownListFor(x=>x.ddlTypeID, new SelectList(Model.ddlTypes,"Key","Value",Model.ddlTypeID),Resources.Globals.msgType)
@Html.ValidationMessageFor(model => model.ddlTypeID)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.firstDate )
</div>
<div class="editor-field">
@Html.EditorFor(model => model.firstDate )
@Html.ValidationMessageFor(model => model.firstDate )
</div>
<div class="editor-label optional">
@Html.LabelFor(model => model.otherDate )
</div>
<div class="editor-field optional">
@Html.EditorFor(model => model.otherDate )
@Html.ValidationMessageFor(model => model.otherDate )
</div>
<input type="submit" value="Save" />
}
Run Code Online (Sandbox Code Playgroud)
这可以隐藏/显示otherDate的字段 - 但是如何在同一时间切换验证?或者有更好的方法吗?
如果你要求 jquery 验证实际上会自动执行此操作
$validator = $("#formName").validate(
{
ignore: ":hidden"
}
Run Code Online (Sandbox Code Playgroud)
我个人认为 JQuery 验证比 MVC 验证更容易使用,但它确实涉及学习如何使用 JQuery 验证(如果您还没有这样做的话)。
(JQuery validate 是一个 JQuery 插件,完全在客户端处理表单验证。)
编辑:删除了一些括号,回想起来,OP显然已经知道了。我很抱歉。
| 归档时间: |
|
| 查看次数: |
10572 次 |
| 最近记录: |