nam vo
nam vo

Reputation: 3437

asp.net mvc dropdownlistfor not show selectedItem

Model:

public partial class BookModel : BaseNopEntityModel, 
               ILocalizedModel<BookLocalizedModel>
{
   public int TranslatorId { get; set; }
   public IList<SelectListItem> AvailableTranslators { get; set; }
}

Controller:

public ActionResult Edit(int id)
{

    var bookTranslators = _customerService.GetAllTranslators();
    foreach (var item in bookTranslators)
    {
        model.AvailableTranslators.Add(new SelectListItem()
        {
            Text = item.Nickname,
            Value = item.Id.ToString(),
            Selected = item.Nickname == model.Translator
         });
    }   
    return View(model);
}

Model.AvailableTranslators does have one item with selected = true but failed to show it as a default value in the View. What am I doing wrong ?

How can i display the selectedItem as the default value ?

View:

@model BookModel 
@Html.DropDownListFor(model => model.TranslatorId, Model.AvailableTranslators)

UPDATE: i changed datatype TranslatorId to string

public string TranslatorId { get; set; }

now dropdownlist shows the correct default value, just don't know why?

Upvotes: 1

Views: 262

Answers (1)

Manish Mishra
Manish Mishra

Reputation: 12375

you need to wrap your AvailableTranslators collection into a SelectList

try this:

@Html.DropDownListFor(s => s.TranslatorId,
                       new SelectList(ViewBag.AvailableTranslatators,
                                      "Value","Text",@Model.TranslatorId
                                     ), 
                    new {})

so basically, a SelectList accepts following:

new SelectList(SelectListItemCollection, ValueFieldName, DataFieldName, 
               SelectedValue);

and you might want to take a relook at SelectedValue field that I've given. See if that is what it should be, but you got the idea right?

and as for, why it doesn't work when it is bound to simple SelectListItem List, read all the answers of this question

Upvotes: 2

Related Questions