0

在我的模型中:

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")

当我调试时,我在 QuestionGroupSelectList 中得到 2 个项目(一个 ID 为 30,一个 ID 为 35),它说 selectedValue 是 35(questionGroupId = 35)

但是 selectedvalue 在视图中不起作用,有什么想法吗?

提前致谢!

4

1 回答 1

1

您应该使用不同的属性将下拉列表值绑定到。您还应该使用视图模型和强类型助手,如下所示:

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

那么你可以有一个控制器动作来填充这个视图模型并将它传递给视图:

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);
}

最后在你看来:

@model MyViewModel

@Html.DropDownListFor(
    x => x.QuestionGroupId, 
    Model.QuestionGroupSelectList, 
    "Choose Here"
)
于 2011-09-13T20:55:28.017 回答