How to make a field required on razor view?

2019-04-29 17:29发布

问题:

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');