Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I edit child objects in an MVC4 form?

I have the following:

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

How can I get editing to work for child objects? I tried something like this as well:

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

To pass an 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 to this? What am I missing? Do I need to use an Editor Template? If so, any MVC4-compatible examples would be fantastic.

like image 279
RobVious Avatar asked Mar 05 '13 21:03

RobVious


1 Answers

is there a simple solution to this?

Yes.

What am I missing?

Editor templates.

Do I need to use an Editor Template?

Yes.

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

ASP.NET MVC 4? Man, editor templates exist since ASP.NET MVC 2. All you need to do is to use them.

So start by getting rid of the outer foreach loop and replacing it with:

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

and then obviously define an editor template that will be rendered automatically for each element of the Parents collection (~/Views/Shared/EditorTemplates/Parent.cshtml):

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

and then an editor template for each element of the Children collection (~/Views/Shared/Editortemplates/Child.cshtml) where we will get rid of the inner foreach element:

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

everything works by convention in ASP.NET MVC. So in this example I assume that Parents is an IEnumerable<Parent> and Children is an IEnumerable<Child>. Adapt the names of your templates accordingly.

Conclusion: everytime you use foreach or for in an ASP.NET MVC view you are doing it wrong and you should consider getting rid of it and replacing it with an editor/display template.

like image 155
Darin Dimitrov Avatar answered Oct 24 '22 02:10

Darin Dimitrov