1 year ago

#379351

test-img

Neutrino

How do I bind a Razor partial to a sub-property of its parent's model?

I have a form in a Razor page containing loads of fields, all with identical markup.

@page "{id:int}"
@model RazorPagesMovie.Pages.Movies.EditModel

<form method="post">
   <div class="form-group">
      <label asp-for="Movie.Title" class="control-label"></label>
      <input asp-for="Movie.Title" class="form-control" />
      <span asp-validation-for="Movie.Title" class="text-danger"></span>
   </div>
   <div class="form-group">
      <label asp-for="Movie.ReleaseDate" class="control-label"></label>
      <input asp-for="Movie.ReleaseDate" class="form-control" />
      <span asp-validation-for="Movie.ReleaseDate" class="text-danger"></span>
   </div>
   <div class="form-group">
      <label asp-for="Movie.Genre" class="control-label"></label>
      <input asp-for="Movie.Genre" class="form-control" />
      <span asp-validation-for="Movie.Genre" class="text-danger"></span>
   </div>
</form>

Rather than my page file being stuffed with all this copy/paste I decide to eliminate the code duplication using the feature the ASP documentation says I should be using for this, namely a partial.

So I create a partial

@model object

<div class="form-group">
   <label asp-for="@Model" class="control-label"></label>
   <input asp-for="@Model" class="form-control" />
   <span asp-validation-for="@Model" class="text-danger"></span>
</div>

...and reference that from my page file using

<partial name="_MovieField" for="Movie.Title" />

Only problem, nothing works. The asp-for="@Model" in the label doesn't resolve the display name for the property so the label is blank, and none of the validation works either.

It seems that if this can be make to work then some kind of specific technique is required to pass a sub-property of a model to a partial in such a way that any tag helpers will still work. Unfortunately the ASP Core documentation doesn't provide any clue as to go about this.

Does anyone know how to get this to work?

asp.net-core

razor

razor-pages

0 Answers

Your Answer

Accepted video resources