I have taken a look at but it did not help me out
- GetFullHtmlFieldId returning incorrect id attribute value
- ASP.NET GetFullHtmlFieldId not returning valid id
Problem
Basically I have the following problem:
I have a custom validation attribute which requires to get the fieldId of the control
public class MyValidationAttribute : ValidationAttribute, IClientValidatable
{
//...... Collapsed code
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ViewContext vwContext = context as ViewContext;
var fieldId = vwContext.ViewData.TemplateInfo.GetFullHtmlFieldId(metadata.PropertyName);
//...... Collapsed code
yield return clientValidationRule;
}
//...... Collapsed code
}
The result of GetFullHtmlFieldId
depends on how I build my asp.net mvc page:
// Edit.cshtml or Create.cshtml
@Html.EditorFor(model => model.MyBoolProperty)
// Shared/EditorTemplates/Boolean.cshtml
@Html.CheckBoxFor(model => model)
result of GetFullHtmlFieldId
incorrect: MyBoolProperty_MyBoolProperty
// Edit.cshtml or Create.cshtml
@Html.CheckBoxFor(model => model.MyBoolProperty)
result of GetFullHtmlFieldId
correct: MyBoolProperty
Even with more complex editors I see this incorrect behavior
// Edit.cshtml or Create.cshtml
@Html.EditorFor(model => model.JustAnArray[1].ComplexProperty.MyBooleanProperty)
// Shared/EditorTemplates/Boolean.cshtml
@Html.CheckBoxFor(model => model)
result of GetFullHtmlFieldId
incorrect: JustAnArray_1__ComplexProperty_MyBoolProperty_MyBoolProperty
// Edit.cshtml or Create.cshtml
@Html.CheckBoxFor(model => model.JustAnArray[1].ComplexProperty.MyBooleanProperty)
result of GetFullHtmlFieldId
correct: JustAnArray_1__ComplexProperty_MyBoolProperty
Also this is returning correct value
// Edit.cshtml or Create.cshtml
@Html.EditorFor(model => model.JustAnArray[1])
// Shared/EditorTemplates/ComplexProperty.cshtml
@Html.CheckBoxFor(model => model.MyBooleanProperty)
result of GetFullHtmlFieldId
correct: JustAnArray_1__ComplexProperty_MyBoolProperty
It looks like that using @Html.CheckBoxFor(model => model)
, it gives incorrect results but when using @Html.CheckBoxFor(model => model.MyBoolProperty)
it is working as expected
I have the same issue with other controls (like TextBoxFor
)
Question
How can I get the proper fieldId of my control in my validation attribute, independent of how you build the page.
I'd rather use already existing methods (maybe the same methods as which are used by TextBoxFor and CheckBoxFor and other controls) than mimic this already existing functionality. If I mimic the generation of the fieldId, I have a change I don't take care of all situations where the ASP.NET controls take care of.