How to edit child objects in MVC4 form?

I have the following:

@foreach (var parent in Model.Parents)
{      
    @foreach (var child in parent.Children)
    {    
        @Html.TextAreaFor(c => child.name)    
    }                   
}

How do I set up editing for child objects? I also tried something:

<input type="hidden" name="children.Index" value="@child.Id" />
<textarea name="children[@child.Id]" >@child.Name</textarea>

To pass IDictionary to the controller, but I get an error:

[InvalidCastException: Specified cast is not valid.]
   System.Web.Mvc.CollectionHelpers.ReplaceDictionaryImpl(IDictionary`2 dictionary, IEnumerable`1 newContents) +131

This seems like a very common task ... is there a simple solution? What am I missing? Do I need to use an editor template? If so, then any examples compatible with MVC4 would be fantastic.

+5
source share
1 answer

Is there a simple solution?

Yes.

What am I missing?

Editor Templates.

Do I need to use an editor template?

Yes.

If so, any examples compatible with MVC4 would be fantastic.

ASP.NET MVC 4? , ASP.NET MVC 2. , , .

, foreach :

@model MyViewModel
@Html.EditorFor(x => x.Parents)

, , , Parents (~/Views/Shared/EditorTemplates/Parent.cshtml):

@model Parent
@Html.EditorFor(x => x.Children)

Children (~/Views/Shared/Editortemplates/Child.cshtml), foreach:

@model Child
@Html.TextAreaFor(x => x.name)

ASP.NET MVC. , Parents IEnumerable<Parent> Children IEnumerable<Child>. .

: , foreach for ASP.NET MVC, , , /.

+11

All Articles