Problem to add Dropdownlist to Create view

Mar 29, 2011 at 3:39 PM

when i learn to  add dropdownlist to the create view,it throw a exception:the value can not be null.this is the code

        public ActionResult Create()
        {
            ViewBag.Genres = musicStore.Genres.OrderBy(g => g.Name).ToList();
            ViewBag.Artists = musicStore.Artists.OrderByDescending(a =>a.Name).ToList();
            Albums album = new Albums();
            return View(album);
        }

 

 @Html.DropDownList("GenreId",
                 new SelectList(ViewBag.Genres as System.Collections.IEnumerable,
        "GenreId", "Name", Model.GenreId))
            @Html.ValidationMessageFor(model => model.GenreId)
        </div>

        <div class="editor-label">
            @Html.Label("Artist")
        </div>
        <div class="editor-field">
            @Html.DropDownList("ArtistId",new SelectList(ViewBag.Genres as System.Collections.IEnumerable,
        "GenreId", "Name", Model.GenreId))
            @Html.ValidationMessageFor(model => model.ArtistId)
        </div>

 

i hope someone who can help me.it  exact  made me crazy

Coordinator
Mar 30, 2011 at 8:13 AM

You have a typo in your Artist dropdown - you're matching on GenreId, but you should be matching on ArtistId. Here's what you have:

 

@Html.DropDownList("ArtistId",new SelectList(ViewBag.Genres as System.Collections.IEnumerable, "GenreId", "Name", Model.GenreId))

It should be:

@Html.DropDownList("ArtistId",new SelectList(ViewBag.Artists as System.Collections.IEnumerable, "ArtistId", "Name", Model.ArtistId))
Make sense?