2

I have an aspx page which allows me to edit articles. Among things I can edit is which category the article belongs to. The category is chosen through a DropDownList as shown here,

<%= Html.DropDownList("categoryID", (IEnumerable<SelectListItem>)ViewData["CategoryID"], new { @class = "textbox" }) %>

However, the articles category isn't selected when I go to that page. The ViewData I use for the DropDownList looks like this,

ViewData["CategoryID"] = new SelectList(categories, "CategoryID", "Title", article.CategoryID);

Which should select the article.CategoryID as it's selected value. Have I done this wrong?

2 Answers 2

1

You're assigning the ViewData property a SelectList, but casting it to IEnumerable<SelectListItem> - try typing directly to SelectList instead:

<%= Html.DropDownList("categoryId", (SelectList)ViewData["CategoryID"], new { @class = "textbox" }) %>
Sign up to request clarification or add additional context in comments.

1 Comment

No, this made no difference. When going to editArticle.aspx the dropdownlist is still not displaying the correct category for the article.
0

The best I could suggest is that you ensure your "Category" class has a property called "CategoryID" and is not just "ID". From what you've given us that's the best guess I can make as to the problem.

If it is just "ID", then your function will need to go:

ViewData["CategoryID"] = new SelectList(categories, "ID", "Title", article.CategoryID);

Comments

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.