niico
niico

Reputation: 12729

ASP.NET MVC 5 site - edit view not selecting item in DropDownListFor

I have an MVC 5 site...

A story can be optionally associated with a PlaceId. A blank placeId is also valid. A place can be associated with more than one story.

Models

public class Place
{
    public Guid Id { get; set; }
    public string PlaceName { get; set; }
}   

public class Story
{
    public Guid Id { get; set; }
    public Guid? PlaceId { get; set; }
    public string StoryName { get; set; }
}

I have several requirements.

Controller (Get)

public ActionResult Edit(Guid Id)
{
    // Get Story
    var story = StoryRepo.SelectArticle(Id);

    // Put select list of all places in ViewBag
    ViewBag.PlaceId = new SelectList(PlaceRepo.SelectAll(), "Id", "PlaceName", new { Id = story.PlaceId });

    // Return view
    return View(story);
}

In View

@Html.DropDownListFor(x => x.PlaceId, (IEnumerable<SelectListItem>)ViewBag.PlaceId, "No Associated Place",
                                    new { @class = "form-control" })

This populates the dropdown list fine, and when you select an item the PlaceId is in the model bound to the controller. However - it does not select the existing PlaceId when the view loads.

Shouldn't the final parameter in the ViewBag.PlaceId line new { Id = story.PlaceId } - cause this selection?

I can't find anything on this specific issue online - and can find little about how to bind a dropdown to a strongly typed edit view in the way I require.

How can I make it select the correct item? (also any improvements on how I am doing this also appreciated).

Thanks.

Upvotes: 2

Views: 1543

Answers (1)

Monah
Monah

Reputation: 6784

I think you need to change the following code

   // Put select list of all places in ViewBag
    ViewBag.PlaceId = new SelectList(PlaceRepo.SelectAll(), "Id",
                             "PlaceName", new { Id = story.PlaceId });

to become

   // Put select list of all places in ViewBag
    ViewBag.PlaceId = new SelectList(PlaceRepo.SelectAll(), "Id", 
                             "PlaceName", story.PlaceId);

Definition of the SelectedList from msdn

SelectList(IEnumerable, String, String, Object): Initializes a new instance of the SelectList class by using the specified items for the list, the data value field, the data text field, and a selected value.

here a working demo

updated demo

Hope this will help you

Upvotes: 1

Related Questions