简体   繁体   中英

ASP.NET MVC DropDownList not setting selected value

Consider the following model:

public class TagType
{
    public int Id { get; set; }
    public string Description { get; set; }
}

public class Tag
{
    public int Id { get; set; }
    public string Description { get; set; }
    public TagType TagType { get; set; }

    public DropDownListViewModel TagTypeViewModel { get; set; }
    public int TagTypeId { get; set; }
}

I have the following Action in a controller:

public ActionResult Edit(int id)
{
    // Load from database
    IEnumerable<TagType> tagTypes = TagTypeDal.GetAll().ToList();
    Tag tag = TagDal.Get(id);

    tag.TagTypeViewModel = new DropDownListViewModel();

    tag.TagTypeViewModel.Items = new List<SelectListItem>();
    tag.TagTypeViewModel.Items.Add(new SelectListItem { Text = "None", Value = "-1" });
    tag.TagTypeViewModel.Items.AddRange(tagTypes
                                        .Select(tt => new SelectListItem 
                                                { 
                                                    Text = tt.Description, 
                                                    Value = tt.Id.ToString(), 
                                                    Selected = tt.Id == tag.TagType.Id 
                                                }).ToList());

    return View(tag);
}

The select list has one element that has Selected=true , and it's not the first element. And on my Edit.cshtml I have:

@model Models.Tag

@Html.DropDownListFor(model => model.TagTypeId,
                      @Model.TagTypeViewModel.Items,
                      new { @class = "form-control" })

My problem is that the generated drop down never selects the element that has Selected=true , it always shows the first element.

Am I calling the wrong overload for DropDownListFor ? Or am I building the select list wrong? Or is it somethig else?

You should fill model.TagTypeId with selected TagTypeId in your Controller .

DropDownListFor selected value depends on first parameter value.

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