Search code examples
asp.net-core-mvc.net-7.0

ASP.Net Core MVC Referential Partial Views Referencing Parent View Models


I'm trying to create some reusable components in an ASP.Net Core MVC on Net 7. I can't seem to figure out how to create a main page/view with partial views embedded that reference the main pages model.

So where I have a class something like the following as the @model for my main page...

public class MyMainModel
{
   string Property1;
   string Property2;
   List<string> Property3 = new List<string>();

}

I want that main page, Index.cshtml for example, to have a partial view that manages the Property3 on the Index.cshtml.

So far, it seems like PartialViews, ViewComponents, etc, all function in a way that they clone the object passed to them. So any updates made by the PartialView or ViewComponent never make it back to the Index.cshtml pages @model.

So if I pass the list of Property3 over to a PartialView or ViewComponent, the cloned List does get updated, but it's not updating Propery3 @model of the Index.cshtml.

What am I missing?


Solution

  • A simple working demo you could follow:

    Model

    public class MyMainModel
    {
        public string Property1 { get; set; }
        public string Property2 { get; set; }
        public List<string> Property3 { get; set; }          
    }
    

    Main View

    @model MyMainModel
    <form asp-action="Update" method="post">
        <input asp-for="Property1" />
        <input asp-for="Property2" />
        <partial name="_partial" for="@Model.Property3" />
        <input type="submit" value="UPDATE" />
    </form>
    

    Partial View

    @model List<string>
    @for(int i=0;i<Model.Count();i++)
    {
        <input asp-for="@Model[@i]" name="Property3[@i]" type="text"/>
    }
    

    Controller

    public async Task<IActionResult> Index()
    {
        var model = new MyMainModel()
        {
            Property1 = "aa",
            Property2 = "bb",
            Property3 = new List<string>() { "p1", "p2" }
        };
        return View(model);
    }
    [HttpPost]
    public IActionResult Update([FromForm]MyMainModel model)
    {
        //do your stuff...
    }