开发者

How to bind a ViewModel that has sub-viewmodel properties?

I am curious to know the best way to approach the following scenario:

public class LittleThingViewModel
{
    public string Id{ get; set; }
    public string Name { get; set; }
    public string Location { get; set; }
}

public class BigThingViewModel
{
    public LittleThingViewModel little1 {get; set; }
    public LittleThingViewModel little2 {get; set; }
    public string propA {get; set; }
    public string propB {get; set; }
    public string propC {get; set; }
}

In the initial CREATE action of my controller, I populate two LittleThingViewModels, assign them to a new BigThingViewModel and pass it to the strongly-typed view. I then use EditorFor to render edit controls for BigThing properties A, B, and C.

Wha开发者_运维知识库t is the best technique for automatically rendering the LittleThingViewModels to the form such that when I post back to my controller it auto-binds? (My goal is to only display the Name and keep the other properties hidden)

public ActionResult Create(BigThingViewModel b) 

I found that I could render A, B, and C properties in addition to each individual property of the two LittleThing sub-viewmodels and it successfully bind BigThingViewModel during POST:

Html.DisplayFor(model=>model.little1.Name)
Html.HiddenFor(model=>model.little1.Name)
Html.HiddenFor(model=>model.little1.Id)
Html.HiddenFor(model=>model.little1.Location)

Is there a technique that would allow me to render both labels and hidden elements automatically instead of having to do them each explicitly each time?

Something like:

Html.RenderFor(model=>model.little1)

Thanks


Create a partial view that is strongly typed to the LittleThingViewModel.

LittleThingView.ascx (partial view)

Html.DisplayFor(model=>model.Name)
Html.HiddenFor(model=>model.Name)
Html.HiddenFor(model=>model.Id)
Html.HiddenFor(model=>model.Location)

In main View

<%
Html.RenderPartial("LittleThingView",model.little1);
Html.RenderPartial("LittleThingView",model.little2);
%>

To make it look better you can make a collection for these objects in the big ViewModel. So if one of them is null or you need more than one, it wouldn't need any changes.

public class BigThingViewModel
{
    public List<LittleThingViewModel> littles=new List<LittleThingViewModel>();
    public string propA {get; set; }
    public string propB {get; set; }
    public string propC {get; set; }
}

And in the view:

<%
foreach(var littleThingViewModel in model.littles)
{
    Html.RenderPartial("LittleThingView",littleThingViewModel);
}
%>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜