samedi 8 février 2020

How to get model property name in a partial view

I have a partial view that takes this view model:

// MyApp.MyPartialViewModel.cs
public class MyPartialViewModel {
  public string MyProperty { get; set; }
}

The partial view renders input elements for its view model, like this:

@* MyPartialViewModel.cshtml *@
@model MyApp.MyPartialViewModel
<input asp-for="MyProperty" />

Now, the partial view is referenced in a parent view whose view model looks like this:

// MyApp.MyViewModel.cs
public class MyViewModel {
  public MyPartialViewModel MyPartialViewProperty { get; set; }
}

And, finally, the parent view (displayed by the controller) looks like this:

@model MyApp.MyViewModel
<form method="post">
  <partial name="MyPartialView" model="@Model.MyPartialViewProperty" />
</form>

My question is: Is there a way, in the partial view (or in code called from the partial view) to get the name of the property bound to the Model? In other words, I want to discover that (in this example) my model is bound to a property named MyPartialViewProperty (that is, the name of the property in the parent view model).

So, why do I need this, you ask? Because in order for the model binding in the controller POST routine to work correctly, I need to prefix the <input> element's name attribute with the property name, like this:

<input name="MyPartialViewProperty.MyProperty" asp-for="MyProperty" />

so I need some code that can fabricate the prefix based on the name of the property in the parent view model that becomes the view model for the partial view.





Aucun commentaire:

Enregistrer un commentaire