Using ASP.NET MVC 3 with Razor, what is the most efficient way to add ICollection to the Create view?

I am using the Entity Framework Code First to create my database, so I have an object defined as follows:

public class Band
{
    public int Id { get; set; }
    [Required(ErrorMessage = "You must enter a name of this band.")]
    public string Name { get; set; }
    // ...
    public virtual ICollection<Genre> Genres { get; set; }
}

Now I am looking at creating a presentation for this, and by default scaffolding does not add genres to my form, which are from past experiences about what I expect.

While searching online, I found Using ASP.NET MVC v2 EditorFor and DisplayFor with IEnumerable <T> Generic types , which seems to be closest to what I want, but doesn't seem to make sense with Razor and possibly MVC 3 , for ASP.NET MVC 3 Custom Display Template With UIHint - for Loop Required? .

Currently, I added a list of genres to the ViewBag, and then scrolled the list in my creation view:

@{
    List<Genre> genreList = ViewBag.Genres as List<Genre>;
}
// ...
<ul>
@for (int i = 0; i < genreList.Count; i++)
{
    <li><input type="checkbox" name="Genres" id="Genre@(i.ToString())" value="@genreList[i].Name" /> @Html.Label("Genre" + i.ToString(), genreList[i].Name)</li>
}
</ul>

Unless the user has turned off JavaScript, and the checkboxes need to be double-checked and actually update the database using this information, it displays genres as I would like.

But that doesn't seem right based on how good MVC 3 is.

So what is the most efficient way to handle this in MVC 3?

+5
source share
1 answer

I do not send lists to my view through the ViewBag, instead I use my view model for this. For example, I did something like this:

I have an EditorTemplate like this:

@model IceCream.ViewModels.Toppings.ToppingsViewModel
<div>
   @Html.HiddenFor(x => x.Id)
   @Html.TextBoxFor(x =x> x.Name, new { @readonly="readonly"})
   @Html.CheckBoxFor(x => x.IsChecked)
</div>

Views\IceCream\EditorTemplates. , html, "" - .

- :

@HtmlEditorFor(model => model.Toppings)

EditorTemplate, Toppings .

viewmodel, , , Toppings:

public IEnumerable<ToppingsViewModel> Toppings { get; set; }

, , ( , ) viewmodel . , , IsChecked TopingsViewModel, .

, , , . , , .

+5

All Articles