2

Expanding on a previous question, I'm using EditorFor to edit a list of objects of type (let's say) Hobby.

Now, I need to implement functionality to add editors for individual Hobby objects, so that the user can add additional hobbies.

I read Steven Anderson's blog about how to do that in MVC 2. However, he's rendering the individual Hobby instances using a loop and RenderPartial, rather than using EditorFor. I understand his approach of making Ajax calls to render another partial view and inserting the view result into the DOM, but don't know how to apply the Ajax add in my case, with EditorFor.

His code:

<% foreach (var item in Model)
    Html.RenderPartial("GiftEditorRow", item);
%>

My code is using EditorFor like this:

// Model is a List<Hobby>
@Html.EditorFor(model => model.AllowedSurveys)

How do I add an additional Hobby editor, given that the editor is implemented as an Editor Template rather than as a Partial View?

1 Answer 1

3

You could replace your editor template with a partial:

@foreach (var item in Model.AllowedSurveys)
{
    Html.RenderPartial("_Hobby", item);
}

and inside the partial (~/Views/controllerName/_Hobby.cshtml):

@model Hobby
<div class="editorRow">
    @using(Html.BeginCollectionItem("AllowedSurveys")) 
    {
        @Html.EditorFor(x => x.Name)
        ...
    }
</div>

The Html.BeginCollectionItem custom helper is used to generate names with Guids and allow for reordering and adding new items to the collection using javascript. You can download it from the updated article. The one you were reading was for ASP.NET MVC 1 and is obsolete.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.