c# - MVC Razor EditorFor Last Object in List -


i'm trying display editorfor last child object in collection. below pocos order (parent) , hold (child collection):

public class order {     public int id {get;set;}     public string name {get;set;}     ....     public virtual list<hold> holds { get; set; } }  public class hold {     public int id { get; set; }     public int orderid { get; set; }     public virtual order order { get; set; }     public datetime? when { get; set; }     public string reason { get; set; } } 

here's attempt @ creating order view shows order , last hold if there 1 present. i've commented out last hold attempt doesn't work.

@model order  @using (html.beginform("update", "order", formmethod.post, new {})) {    <div class="form-group row">       @html.labelfor(x => x.name, new { @class = "col-xs-2" })       <div class="col-xs-10">          @html.editorfor(x => x.name, new { @class = "form-control"})       </div>    </div>     <div class="form-group row">       <label class="col-xs-2">when</label>       <div class="col-xs-10">          @*@html.editorfor(x => x.holds.last().when, new {})*@       </div>    </div> } 

the holds collection can null doing last() in case case null exception if did work.

this seems simple , have pattern in couple places in database. can recommend way handle situation?

thanks!

you should use view model because wont response in httppost action when post back

public class orderviewmodel {     public orderviewmodel()     {         order = new order();         hold = new hold();     }     public order order { get; set; }     public hold hold { get; set; } }  public actionresult edit(int id) {      var o = o context.order.include("holds").single(id);     var model = new orderviewmodel()     {         order = o     }     if (o.holds.count() > 0)         model.hold = o.holds.last();     return view(model); } 

then use editorfors

@model orderviewmodel  @using (html.beginform("update", "order", formmethod.post, new {})) {    <div class="form-group row">       @html.labelfor(x => x.order.name, new { @class = "col-xs-2" })       <div class="col-xs-10">          @html.editorfor(x => x.order.name, new { @class = "form-control"})       </div>    </div>     <div class="form-group row">       <label class="col-xs-2>when</label>       <div class="col-xs-10">          @html.editorfor(x => x.hold.when)       </div>    </div> } 

Comments