0

Trying to use a view model that includes a complex property that I would like to edit and persist on post back

public class MyViewModel
{
    public string SearchTerm1 {get;set;}
    public string SearchTerm2 {get;set:}
    public NavStuff NavStuff {get;set:}
    public virtual ICollection<Stuff> StuffIWant{ get; set; }
}
public class NavStuff
{
    public bool Next {get;set;}
    public bool Back {get;set;}
    .....
}

I'd like to use it this way so I can send the NavStuff to a partial view

@Html.Partial("NavStuffPartial", Model.NavStuff)

This works fine on the initial Get but when I post the model back I lose the data in NavStuff. Is there a way to do this or am I just going in the wrong direction? Thanks

clarence_odbody
  • 185
  • 2
  • 16
  • 1
    A partial will not work (unless you also pass the `HtmlFieldPrefix` - refer [getting the values from a nested complex object that is passed to a partial view](https://stackoverflow.com/questions/29808573/getting-the-values-from-a-nested-complex-object-that-is-passed-to-a-partial-view/29809907#29809907)) but that wont work with an `ICollection` anyway. –  Nov 09 '18 at 23:19
  • 1
    The correct approach is to use an `EditorTemplate` - refer [https://stackoverflow.com/questions/30094047/post-an-html-table-to-ado-net-datatable/30094943#30094943](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943) (and the collection should be `public IEnumerable StuffIWant{ get; set; }` or `List` i you use a `for` loop –  Nov 09 '18 at 23:20
  • @StephenMuecke - I'm looking to get the data for the NavStuff which is just a couple of bools, not a collection. – clarence_odbody Nov 09 '18 at 23:28
  • It still the same - read the links! If you use a partial then you must pass the `HtmlFieldPrefix` so that you generate the correct `name` attributes` - i.e. `name="NavStuff.Next"` etc. Or better, use an `EditorTemplate` (the comment on the collection is just extra info - a view model should not contain data models, and its properties should not be `virtual`) –  Nov 09 '18 at 23:32
  • sorry I misunderstood - checking it out now – clarence_odbody Nov 09 '18 at 23:36
  • To make it clearer, create a partial view named `NavStuff.cshtml` in the `Views/Shared/EditorTemplates` folder with `@model NavStuff` and in the main view use `@Html.EditorFor(m => m.NavStuff)` –  Nov 09 '18 at 23:39
  • That worked very nicely~ thanks! – clarence_odbody Nov 09 '18 at 23:47

0 Answers0