Julian
Julian

Reputation: 1113

ASP.NET MVC - Adding multiple items to a list

I've got the next question about the right way of adding items to a list in MVC.

Let's say I got the following model:

public class Student
{
    public String Name { get; set; }
    public List<Lesson> Lessons { get; set; }
}

Now I'm in the Student Create view in which the user can add multiple Lessons. The way the view looks is that there is a dropdown in which you can select a lesson and a button to add a new dropdown. This way a person can add multiple lessons to the Lessons variable.

Now I tried alot of different approaches but never seemed to have the right one because I don't like having this in the view:

 @Html.DropDownListFor(model => model.Lessons[0].Id, new SelectList(...), "Select lesson")

And change the 0 to 1..2 etc with jquery or what so ever.

What are your approaches on those views in which you dynamicly add multiple items?

Upvotes: 1

Views: 2442

Answers (1)

beyond-code
beyond-code

Reputation: 1422

You should look at defining an editor template:

If you write your template correctly, asp.net will render controls with the names similar to:

Lesson[0]_Title

UPDATE: Here's how:

Create a folder in views\shared called EditorTemplates Then create a partial view with a model of type Lesson inside here. Make sure you call this partial view "Lesson.cshtml" (or ascx if you're not using razor)

Then you can do...

@Html.EditorFor(model => model.Lessons) 

...and asp.net will magically figure out that because Lessons is an IEnumerable of lesson, it should loop and render an editor for each one. Pretty neat!

Some links:

http://forums.asp.net/t/1846290.aspx/1?Editor+template+of+type+IEnumerable+SelectListItem+with+MVC+area

Upvotes: 2

Related Questions