I'm using the .net core framework with razor pages without MVC and I'm trying to integrate a form with a view component to make it reusable.
The problem is I noticed that it's not really made for. Indeed I use the asp-for attribute of the form which in reality is based on the parent PageModel in which I have bound an attribute corresponding to the field of my form.
I would like to know how you can create reusable component that contain forms to be used in a final PageModel.
Thank you :)
If you want to make your partial view reusable,it means only one model should be called.
Do you want to use a partial view, and get the data from different models?
Then you can use a ViewModel to contain multiple different models,like:
public class MyViewModel
{
public Profile Profile { get; set; }
public Job Job { get; set; }
}
public class Profile
{
public string Name { get; set; }
}
//....other models
Index.cshtml.cs:
[BindProperty]
public MyViewModel MyViewModel { get; set; }
public void OnGet()
{
MyViewModel = new MyViewModel
{
Job = new Job { Name = "teacher" },
Profile=new Profile {Name="Peter"}
};
}
Index.cshtml (model= is used to pass model to partial):
<partial name="~/Pages/Shared/Partialview.cshtml" model="Model.MyViewModel" />
Then you can get the related model data in Partial view:
@model tr4cks491.Models.MyViewModel
<form method="post">
<input asp-for="Job.Name" />
<input asp-for="Profile.Name" />
<input type="submit" value="Submit" />
</form>