简体   繁体   中英

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.

  • When editing the story I would like a drop down list of all places to be displayed - with the associated place (if any) - selected.
  • I want to use the strongly typed DropDownListFOR (as opposed to DropDownList).
  • I want to add a "No Associated Place" which will be selected if PlaceId is null (and should pass null back to the model).
  • I want to add a css class = "form-control" to the DropDownListFor.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM