在我的模特中:
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为Id 30,另一个ID为Id 35),并且它表示selectedValue为35(questionGroupId = 35)
但是selectvalue在视图中不起作用,有什么想法吗?
提前致谢!
答案 0 :(得分: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"
)