大家早上好。
出于某种原因,我在模型的下拉列表上有一层服务器端验证:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (SomethingVisible && DropDownListSelection == 0)
{
yield return new ValidationResult("Please make a selection", new[] { "DropDownListSelectionId"});
}
}
<div class="editor-field">
@Html.DropDownListFor(x => x.DropDownListSelectionId, new SelectList(Model.DropDownListSelection, "DropDownListSelectionId", "DropDownListSelectionName"))
<br />
@Html.ValidationMessageFor(model => model.DropDownListSelectionId)
</div>
这工作正常而且花花公子,并在 !Model.IsValid 时显示适当的验证错误。可爱。
但是,由于某些此类表单可能非常高(我知道,我知道,很讨厌)并且此验证可能会丢失,即您必须向下滚动才能看到验证错误,有些人不喜欢滚动。
因此,我想做的是使用 jquery/javascript 将焦点设置在经过验证的元素上,我该怎么做呢?
很抱歉这个粗问题。
最佳答案
$(function(){
$('input, select, textarea').each(function(){
if($(this).hasClass('input-validation-error'))
$(this).focus();
});
});
关于javascript - 服务器端验证后如何设置对元素的关注-MVC 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12508903/