2

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?

1
  • 2
    The Selected property of SelectListItem is ignored when binding to a property in your model. Its the value of the property which determines what is selected. Set the value of TagTypeId to a value which matches one of your options and it will be selected Commented Sep 22, 2015 at 9:49

1 Answer 1

1

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

DropDownListFor selected value depends on first parameter value.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that was it. So that means the Selected property of the SelectListItem does nothing at all when binding to a property...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.