Let’s say I have some model objects that resemble this:
public class FooModel
{
[Required]
public string Name { get; set; }
[StringLength(100)]
public string Description { get; set; }
public bool HasBar { get; set; }
public BarModel Bar { get; set; }
}
public class BarModel
{
[Required]
public string Name { get; set; }
[StringLength(100)]
public string Description { get; set; }
public bool HasWidgets { get; set; }
public IEnumerable<WidgetModel> Widgets { get; set; }
}
public class WidgetModel
{
[Required]
public string Name { get; set; }
[StringLength(100)]
public string Description { get; set; }
public string Type { get; set; }
public bool Active { get; set; }
}
I want to build a view for FooModel that, upon the HasBar input being checked, will load a partial view for Bar, complete with validation (unobtrusive). If Bar‘s HasWidgets is checked, it will load a partial view containing an interface for adding items of type WidgetModel to the form data.
When the form’s submit button is clicked, I would like a complete graph passed to the controller.
I thought I could do something like this with Editor Templates, but my sub-objects are not being named in a way that would be parsed as part of the graph (I expect because they are being added after the fact and are not aware they are part of a bigger model).
Is there a mechanism/ pattern for supporting this sort of thing? I know it’s a bit recursive but do I have to reinvent the wheel to get everything to be named properly?
If your UI allows this solution, I suggest you to load all the models into view at the first, but hide “Bar” (and so “Widget”) section (hide using CSS). Then show them using JavaScript/jQuery.
Even if “Bar” needs to load data depending on “Foo” properties value (and “Widget” depending on “Bar”), it’s always easier to load all elements at the very first step, and then fill them by Javascript or AJAX call.