1

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?

15
  • where is the action name specified in form attribute? Commented Sep 12, 2019 at 13:57
  • <form method="post"> should be like: <form method="post" action="" controller=""> Commented Sep 12, 2019 at 13:58
  • check the rendered controls name attribute value in rendered HTML, is it actual name or actual name append with partialview name. Model Binder exactly check the name attribute value from control with the model property, both should match. Commented Sep 12, 2019 at 14:00
  • 2
    @NomiAli there's none, meaning it is submitted to the same page (it's Razor pages: OnGet() / OnPost()) Commented Sep 12, 2019 at 14:02
  • Change <partial name="_partialForm" model="Model.MyModel" /> to <partial name="_partialForm" model="@Model.MyModel" />. Commented Sep 12, 2019 at 14:02

1 Answer 1

2

The solution was to do ViewData.TemplateInfo.HtmlFieldPrefix = "MyModel"; in the partial.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.