mardi 4 août 2015

C# MVC - Fetch name of property dynamically depending on model

In my MVC-project I have different custom validation-attributes. One of them is to check the value of a property against the value of another property.

As stated in many articles, I add something like

result.ValidationParameters.Add("otherproperty", _otherPropertyHtml);
result.ValidationParameters.Add("comparetype", _compareType);
result.ValidationParameters.Add("equalitytype", _equalityType);

to the returning ModelClientValidationRule object.

My problem now is, that - if my property to check - is encapsulated in another object, validation will not work.

If I create something like

@Html.TextBoxFor(m => m.ValueOne)
@Html.TextBoxFor(m => m.ValueTwo)

validation will work fine as it renders

data-val-otherproperty="ValueTwo"

My problem is for the following

@Html.TextBoxFor(m => m.IntermediateObject.ValueOne)
@Html.TextBoxFor(m => m.IntermediateObject.ValueTwo)

This will render two textboxes with names IntermediateObject_ValueOne and IntermediateObject_ValueTwo. But still

data-val-otherproperty="ValueTwo"

for the first textbox.

How can it be achieved, that data-val-otherproperty has always the correct name of the other property?

My thoughts are something like HtmlHelper<>.NameFor(m => ...) or something that uses reflection?





Aucun commentaire:

Enregistrer un commentaire