3

The model

@model List<Survey.SurveyQuestion>

SurveyQuestion has two properties, QuestionId and QuestionText

Html.DropDownList("Questions", new SelectList(@Model))

@Html.DropDownList("Questions", new SelectList(@Model), "QuestionId", "QuestionText")

Output from above code:

Output from above code:

Unable to use DropDownListFor as it does not recognize field QuestionId (or infact any field).

@Html.DropDownListFor(item => item.QuestionId, new SelectList(Model, 
    "QuestionId", "QuestionText"), "--Select --"))

The below code displays all data correctly:

@foreach (var item in Model)
{
    <p>@item.QuestionId - @item.QuestionText</p>
}
5
  • whats strange about this is your are NOT using a dropdownlistfor. I would recommend it, but since you're not, the error is odd. Commented Feb 24, 2013 at 20:25
  • problem is @Html.DropDownListFor(item => item.QuestionId ...), the QuestionId is not recognized, compiler error. Commented Feb 24, 2013 at 20:29
  • which we could tackle, IF YOU WERE USING A DROPDOWNLISTFOR. I'm stumped cause i see you using a dropdownlist -- no FOR Commented Feb 24, 2013 at 20:30
  • Updated with DropDownListFor code. It does not compile. Commented Feb 24, 2013 at 20:34
  • OK, dropdownlist for requires a model variable to bind to with a lambda. do you know what that means? Commented Feb 24, 2013 at 20:36

1 Answer 1

4

You're setting up your SelectList wrong. Try this instead (added linespaces for readability on SO):

@Html.DropDownList(
    "Questions",
     Model.Select(m => new SelectListItem 
         {
             Value = m.QuestionId.ToString(),
             Text = m.QuestionText
         }))
Sign up to request clarification or add additional context in comments.

4 Comments

yup, thats it. I shouldve looked closer.
@DaveA Hehe yeah those html helper overloads can be a nightmare, mixing the order ofhtml attributes and route values on an actionlink always catches me out :)
Thanks, geez, so stupid of me... just mixed the order. This @Html.DropDownList("QuestionId", new SelectList(@Model, "QuestionId", "QuestionText")) also works.
@AseemGautam Np glad I could help :). Just a side note, you don't need the @ before the word Model, as you're already in Razor code (inside the DropDownList call) :)

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.