3

I have this bizarre question, but it is bothering me a lot. I have this css class:

class="form-control"

And I need to use it in my DropDown:

@Html.DropDownList("destination", ((SelectList)ViewBag.DropList).Select(t => new SelectListItem() { Text = t.Text, Value = t.Text, Selected = (t.Text == ViewBag.Destination)}), (SelectList)ViewBag.DropList)

2 Answers 2

6

It seems you are trying to set the SelectedValue of a SelectList within the DropDownList helper which is not possible.

You have to set the SelectedValue property when you create the SelectList. See following example.

ViewBag.DropList = new SelectList(new[]{
    new SelectListItem{ Text="one", Value="1"},
    new SelectListItem{ Text="two", Value="2"},
    new SelectListItem{ Text="three", Value="3"}
    }, "Value", "Text", 2);

In the above code, I have set 2 as selected item when the SelectList is initialized. After that you can pass the SelectList and HTML attributes as below.

@Html.DropDownList("destination", (SelectList)ViewBag.DropList, new { @class = "form-control" })

Thanks!

Solution:

@Html.DropDownList("destination", ((SelectList)ViewBag.DropList).Select(t => new SelectListItem() {Text = t.Text, Value = t.Text, Selected = (t.Text == ViewBag.Destination)}), new{@class="form-control"})
Sign up to request clarification or add additional context in comments.

4 Comments

Can you help me to edit my code for DropDownList in controller. I have post it in my question...
Is this DropDownList for CustomTypes ? Does parameters.Destination contains the selected value ?
I have solve it, I will post solution in your answer. Thanks man, your answer works :D
Did you post it ? I didn't delete anything.
1

The last argument can be an object with html attributes, see msdn:

@Html.DropDownList("destination", ..., new { @class = "form-control" })

2 Comments

Could you post the latest version of the code? Does it match one of these signatures? msdn.microsoft.com/en-us/library/…
Error is this: CS1928: 'System.Web.Mvc.HtmlHelper<AdminRole.Models.SpremenljivkeView>' does not contain a definition for 'DropDownList' and the best extension method overload 'System.Web.Mvc.Html.SelectExtensions.DropDownList(System.Web.Mvc.HtmlHelper, string, System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>, string, object)' has some invalid arguments

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.