swiftcode
swiftcode

Reputation: 3059

Dropdownlist ASP.NET MVC not updating Model

I have two Model classes like so:

Program:

public class Program
{
    public int ProgramId { get; set; }

    public string Name { get; set; }

    public virtual Playlist chosenPlaylist { get; set; }

    public virtual IList<Playlist> Playlists { get; set; }
}

public class Playlist
{
    public int PlaylistId { get; set; }

    public string Name { get; set; }

    public int NumberVotes { get; set; }

    public virtual IList<Song> Songs { get; set; }
}

In my Edit Program View, I want to update the chosenPlaylist so I can allow the user to select none or one of the Program's Playlists.

For example:

Program 1:

Chosen Playlist: Playlist 1

So the user can then edit and select None (so no playlist), 1 (won't change anything) or 2 and that gets saved to the database.

I've tried to create a dropdownlist in my Controller but it won't update.

Here's what I have in both my GET and POST Edit ActionResults:

ViewBag.chosenId = new SelectList(program.Playlists, "PlaylistId",
"Name", program.chosenPlaylist.PlaylistId);

And in my View:

@Html.DropDownList("PlaylistId", (SelectList)ViewBag.chosenId)

This displays the list fine and pre-selects the chosen Playlist, if there is one (if not, I'll write code for it to default to the first). If there aren't playlists in a Program, that's easy to control.

However, problems:

There are no errors thrown, everything seems to work except for the most important part - updating the database.

Upvotes: 1

Views: 5359

Answers (3)

OutstandingBill
OutstandingBill

Reputation: 2862

Make sure there are no @Html.HiddenFor or similar rendering the same item.

Upvotes: 3

IvanL
IvanL

Reputation: 2485

There's 2 things you can do:

Change @Html.DropDownList("PlaylistId", (SelectList)ViewBag.chosenId) into @Html.DropDownList("chosenPlaylist.PlaylistId", (SelectList)ViewBag.chosenId)

Or use the Html.DropDownListFor(m => m.chosenPlaylist.PlaylistId, (SelectList)ViewBag.chosenId)).

Upvotes: 2

ruffen
ruffen

Reputation: 1719

When using:

@Html.DropDownList("PlaylistId", (SelectList)ViewBag.chosenId)

you have to rename the PlaylistId select list to something that is not the same as the propertyname that stores the selected Id, else it wont be marked as selected.

(which makes sense now that im typing it, you cant store the selected value into something that has the same as the select list)

Basically saying:

@Html.DropDownList("MySelectListId", (SelectList)ViewBag.chosenId)

will work.

You can look at the comments on this issue at codeplex for more information: http://aspnet.codeplex.com/workitem/4932

Upvotes: 0

Related Questions