I have a part of a form in a partial view. The form is partly reusable in different pages:
Page 1 (with CompanyId):
<form method="post">
<partial name="_partialForm" model="Model.MyModel" />
<input asp-for="CompanyId />
<input type="submit" />
</form>
Page 2 (without CompanyId):
<form method="post">
<partial name="_partialForm" model="Model.MyModel" />
<input type="submit" />
</form>
_partialForm:
@model Models.MyModel
<label asp-for="FirstName"></label>
<input asp-for="FirstName />
<span asp-validation-for="FirstName"></span>
<label asp-for="LastName"></label>
<input asp-for="LastName />
<span asp-validation-for="LastName"></span>
MyModel:
[Required]
[DisplayName("First name")]
public string FirstName { get; set; }
[Required]
[DisplayName("Last name")]
public string LastName { get; set; }
public Guid? CompanyId { get; set; }
When I look at the source of the rendered page, the label asp-for
-values are there and the input
-fields are decorated with data-val="true" data-val-required="Required"
, so the binding is OK.
When I post the form, I check if (!ModelState.IsValid)
and if not return Page()
.
The result is, if FirstName or LastName is empty, that ModelState isn't valid, but no validation messages are shown.
If I move the form-tag to the partial view (meaning I cannot keep the CompanyId-field as it shall only be available on a single page), the validation errors shows.
Is there any way to get around this?
The solution was to do ViewData.TemplateInfo.HtmlFieldPrefix = "MyModel"; in the partial.