ASP.NET Core can’t assign span name to local variable

65 Views Asked by At

I add dynamic inputs to my form and when I add I dynamically create a name for my input and set it. But, I can't set the same value to the span asp-validation-for parameter. My code:

@model AnswerViewModel


<fieldset class="row answerrow" style="margin: 20px;" id="@Model.answer.Id">
    <div class="form-group">
        <input type="hidden" asp-for="@Model.answer.Id" name="@Model.NameofAnswerIdInput" value="@Model.answer.Id" ></input>
        <input type="hidden" asp-for="@Model.answer.QuestionId" name="@Model.NameofQuestionIdInput" value="@Model.answer.QuestionId" />


        <div id="@Model.answer.Id" class="d-flex form-group">
            <input required="true" asp-for="@Model.CorrectAnswerId" name="@Model.NameofCorrectAnswerIdRadio" 
                   type="radio" value="@Model.answer.Id" />
            <span asp-validation-for="@Model.NameofCorrectAnswerIdRadio" class="text-danger"></span>
            
            <input id="@Model.answer.Id" required="true" asp-for="@Model.answer.Content" 
                   name="@Model.NameofContentInput" value="@Model.answer.Content" class="form-control ms-2" />
            <span asp-validation-for="@Model.NameofContentInput" class="text-danger"></span>
        </div>
    </div>
</fieldset>

When I check through inspect, the span name is set as "data-valmsg-for="NameofContentInput". How can I set the span name correctly to the "@Model.NameofContentInput"?

1

There are 1 best solutions below

0
Brando Zhang On

The asp-validation-for tag helper is used for the model's property not for the mode's property's name. This is the reason why asp-validation-for="@Model.NameofContentInput" will render as data-valmsg-for="NameofContentInput" not the data-valmsg-for="test".

More details you could refer to the ValidationMessageTagHelper's source coeds.

It will use this method to generate the html, you could find it will generate the html basked on the property name not the value.