-1

Working on MVC 5 app with EF 6. I am loading a dropdownlistfor but the default selected value is not working properly. Any ideas why?

Here's part of my ViewModel...

public class ToolQuestionViewModelEdit
{
    public ToolQuestion ToolQuestion { get; set; }

    public SelectList ToolQuestionCategoryList { get; set; }
    public int SelectedToolQuestionCategory { get; set; }
}

Here is my controller code to fill the select list...

vm.ToolQuestionCategoryList = new SelectList(
    this.db.ToolQuestionCategories,
    "Id",
    "ToolQuestionCategory1",
    ToolQuestion.ToolQuestionCategoryId);

Here's my razor code...

@Html.DropDownListFor(c => c.SelectedToolQuestionCategory,
  Model.ToolQuestionCategoryList as SelectList, 
  new { @class = "form-control" })

In the immediate window, when I debug my code I see the that the selected value is working properly...

? vm.AuditQuestionCategoryList.SelectedValue
  82

82 is the proper value that should be selected. But, the view always defaults to the first item. The dropdown is properly displayed with the correct items so I know it's reading the viewmodel properly.

Any ideas? Seems like I'm doing this write.

WebDevGuy2
  • 1,159
  • 1
  • 19
  • 40
  • 1
    Try setting a value for `SelectedToolQuestionCategory` in your Controller and then pass it to the view – progrAmmar Oct 25 '17 at 02:44
  • Similar issues: https://stackoverflow.com/questions/31261389/setting-default-value-to-html-dropdownlistfor & https://stackoverflow.com/questions/23799091/html-dropdownlistfor-how-to-set-default-value. You can use `SelectListItem.Selected` property to set default value passed to `DropDownListFor`. – Tetsuya Yamamoto Oct 25 '17 at 02:45
  • 1
    Set the `ToolQuestionViewModelEdit.SelectedToolQuestionCategory` to the default value. That's all you need. – CodingYoshi Oct 25 '17 at 02:47
  • @progrAmmar That was it! Thanks! Please make it a normal comment so I can award you the answer. – WebDevGuy2 Oct 25 '17 at 02:48

1 Answers1

1

Try setting a value for SelectedToolQuestionCategory in your Controller and then pass it to the view

progrAmmar
  • 2,606
  • 4
  • 29
  • 58