Search code examples
asp.net-mvcasp.net-mvc-3selectedvalue

MVC3 SelectedValue


In my model:

public SelectList QuestionGroupSelectList { get; set; }

------
List<QuestionGroup> questionGroupList = questionGroupRepository.GetQuestionGroup_BySurveyId(survey.Id);

Dictionary<int, string> questionGroupDictionary = questionGroupList.ToDictionary(l => l.Id, l => l.Name);

QuestionGroupSelectList = new SelectList(questionGroupDictionary, "key", "value", questionGroupId);





---------------------------------------
In view:
@Html.DropDownList("QuestionGroupSelectList", Model.QuestionGroupSelectList, "Choose Here")

When i debug i get 2 items in QuestionGroupSelectList (one with Id 30 and one with Id 35), and it says that the selectedValue is 35 (questionGroupId = 35)

But the selectedvalue does not work in the view, any ideas?

Thanks in advance!


Solution

  • You should use a different property to bind your dropdownlist value to. Also you should use view models and strongly typed helpers, like this:

    public class MyViewModel
    {
        public int QuestionGroupId { get; set; }
        public SelectList QuestionGroupSelectList { get; set; }
    }
    

    then you could have a controller action which populates this view model and passes it to the view:

    public ActionResult Foo()
    { 
        // This collection could come from anywhere 
        // normally you will query a repository here to fetch those values
        var values = new[] 
        {
            new { Key = "1", Value = "item 1" },
            new { Key = "2", Value = "item 2" },
            new { Key = "3", Value = "item 3" },
        }
    
        var model = new MyViewModel
        {
            // preselect the second value
            QuestionGroupId = 2,
            QuestionGroupSelectList = new SelectList(values, "Key", "Value")
        }
        return View(model);
    }
    

    and finally in your view:

    @model MyViewModel
    
    @Html.DropDownListFor(
        x => x.QuestionGroupId, 
        Model.QuestionGroupSelectList, 
        "Choose Here"
    )