I want to add the "data-val-required" and "data-val" attributes to an @html.textbox or an @Html.EditorFor element. Is it possible without rewriting the view?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Normally you should not rewrite the view to achieve that. You should decorate your view model properties with the corresponding validation attributes. For example:
[Required]
public string Foo { get; set; }
Then the Html helpers will generate the correct markup. But if for some weird reason you cannot modify this code you could use javascript in order to add those attributes manually:
$(function() {
$('#id_of_the_field').attr('data-val-required', 'true');
});
Once you add those attributes you need to reparse the validation rules of the form containing those input fields for your changes to take effect:
$('form').removeData('validator');
$('form').removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse('body');