Saeid
Saeid

Reputation: 13592

Select an Item in Html.DropDownListFor() with MVC

I have a table(Collection) of Kinds And in Edit View (in MVC) Need this Kinds in DropDown, Also I Need The DropDown Select Old Kind as Default, But there is some Problems.

This is my Select List:

var Kinds = db.Kinds
                   .Where(n => n.Member.Id == owner.Id)
                   .Select(k =>k.Title);

var selectList = new SelectList(Kinds);

Also The Default Kind(Value) is :

var Selection= db.Kinds
                 .Single(k => k.Numbers
                 .Any(no => no.Id == Model.Id)).Title;

And this is My DropDown:

 @Html.DropDownListFor(model => model.NumberKind.Title, selectList)

When I Define DropDown Like following the new member added at the first of dropdown items:

@Html.DropDownListFor(model => model.NumberKind.Title, selectList, Selection)

For ex if the items be [Mobile, Home, Work] And Selection is [Home] With above Code the items will be like this: [Home, Mobile, Home, Work] but I don't need new item, I just want Select Home From The Main Items How Can I do this?

Thank you

Upvotes: 1

Views: 2247

Answers (1)

Jesse
Jesse

Reputation: 8393

You're currently providing a "default" value for your drop down list. The intended purpose of the dropdownlistfor constructor you are using would be to add an item like "Select Phone" to your drop down list.

Use simply:

@Html.DropDownListFor(model => model.NumberKind.Title, selectList)

Similar question here for reference: DropDownList setting selected item in asp.net MVC

Upvotes: 1

Related Questions