Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does HtmlHelper.GetUnobtrusiveValidationAttributes delete attributes when called?

In asp.net MVC I wanted to retrieve validation attributes of certain fields.

For this I used HtmlHelper.GetUnobtrusiveValidationAttributes() method. The first time being called, it returns a collection of attributes as expected. However, if called a second time, attributes are empty.

example:

var attributes = htmlHelper.GetUnobtrusiveValidationAttributes(propertyName);
var attributes2 = htmlHelper.GetUnobtrusiveValidationAttributes(propertyName);

attributes2 is empty.

This is a problem for me because I check validation attributes of fieldB while rendering fieldA but then when fieldB is rendered, attributes are gone.

Is this a known behaviour ? Am I missing something ? How can I preserv validation attributes betweeen GetUnobtrusiveValidationAttributes calls ?

Thanks in advance

like image 900
Miguel Cruz Avatar asked Nov 28 '25 18:11

Miguel Cruz


1 Answers

This is by design. Html.ViewContext.FormContext contains a list of the fields that it thinks have been rendered; when you call GetUnobtrusiveValidationAttributes the first time it marks your field as rendered, then subsequent calls return an empty collection.

You can set that field as un-rendered by doing this:

Html.ViewContext.FormContext.RenderedField(ViewData.TemplateInfo.GetFullHtmlFieldName(propertyName), false);
like image 153
masty Avatar answered Nov 30 '25 12:11

masty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!