Mariah
Mariah

Reputation: 727

Saving a child object value via parent razor view?

hi how can i get child (contained) value to save correctly in edit view of parent? The value shows up correctly but won't save?

    @model MVC3.Models.A

    @Html.EditorFor(model => model.Bs.First().Val)

    public  class A
    {
        public int Name { get; set; }
        public virtual ICollection<B> Bs { get; set; }
    }

    public  class B
    {
        public int Val { get; set; }
        public virtual A A { get; set; }
    }

Upvotes: 1

Views: 1203

Answers (1)

Jon
Jon

Reputation: 437424

The direct answer would be to refer to the child object using array notation (of course, assuming Children is something that implements IList):

@Html.EditorFor(model => model.Children[0].Val)

If you intend to provide editors for all of the Children though, it would be best to define an editor template for that type and use @Html.EditorFor(model => model.Children) instead of displaying editors for each element in the collection using a loop.

Edit: Corrected ICollection instead of IList error.

Update:

If your collection only implements ICollection (and thus is not indexable), then you should consider using a ViewModel (exposing an IList) instead of the Model you currently use, to make the above valid.

If this is not an option, then you could consider this hack:

// essentially creating the correct name manually
@Html.TextBox(Html.NameFor(m => m.Children) + "[0].Val",
              model.Children.First().Val)

Of course this loses you support for automatically utilizing any editor template you may have, but this might not be a problem in your case (especially considering Val sounds like a simple type).

Upvotes: 1

Related Questions