我有联系表单的主题下拉列表。我总是希望其他人在列表的底部。我问这个的原因是因为我创建了一个控制器,所以如果我想添加更多的主题,我可以这样做。无论如何建议或方法我可以确保其他主题的位置始终位于列表的底部?
public void PrepareSubjectCombo()
{
// Grab a list of subjects for the dialog box
IRepository<Subject> subjectRepository = new Repository<Subject>();
List<Subject> subjects = subjectRepository.GetAll().OrderBy(t => t.Position).ToList();
subjects.Insert(0, new Subject() { ID = 0, Name = "- Please Select -" });
ViewData["Subjects"] = subjects;
}
如果有任何帮助,我已经发布了我的组合框
答案 0 :(得分:1)
在视图中呈现下拉列表时,您应该只使用DropDownList助手的正确重载,而不是尝试将一些虚拟项插入到集合中:
public void PrepareSubjectCombo()
{
// Grab a list of subjects for the dialog box
IRepository<Subject> subjectRepository = new Repository<Subject>();
List<Subject> subjects = subjectRepository.GetAll().OrderBy(t => t.Position).ToList();
ViewData["Subjects"] = subjects;
}
然后在视图中:
@Html.DropDownList(
"selectedSubject",
new SelectList(ViewData["Subjects"] as List<Subject>, "ID", "Name"),
"- Please Select -"
)
现在有人说,每当我看到有人使用ViewData / ViewBag / ViewCrap而不是强类型视图和查看模型时,我就会生病,我觉得自己有义务展示这样做的正确方法。
与往常一样,您从视图模型开始:
public class MyViewModel
{
public string SelectedSubject { get; set; }
public IEnumerable<SelectListItem> Subjects { get; set; }
}
然后你有一个控制器动作,它将负责填充这个视图模型:
public ActionResult Index()
{
// TODO: You definitively don't want to hardcode your repository like this
// but use a constructor injection or this action will be impossible to unit test
IRepository<Subject> subjectRepository = new Repository<Subject>();
var subjects = subjectRepository.GetAll().OrderBy(t => t.Position).ToList();
var model = new MyViewModel
{
Subjects = subjects.Select(x => new SelectListItem
{
Value = x.ID.ToString(),
Text = x.Name
})
};
return View(model);
}
最后在你的强类型视图中:
@model MyViewModel
@Html.DropDownListFor(
x => x.SelectedSubject,
new SelectList(Model.Subjects, "Value", "Text"),
"- Please Select -"
)
答案 1 :(得分:0)
DropDownList1.DataSource = YourDataSource;
DropDownList1.DataBind();
//Insert Other subject to the end
ListItem litem = new ListItem(" Other subject ", "value");
DropDownList1.Items.Insert(DropDownList1.Items.Count, litem);
答案 2 :(得分:-1)
修改您的代码,如下所示:
public void PrepareSubjectCombo()
{
// Grab a list of subjects for the dialog box
IRepository<Subject> subjectRepository = new Repository<Subject>();
List<Subject> subjects = subjectRepository.GetAll().OrderBy(t => t.Position).ToList();
subjects.Insert(0, new Subject() { ID = 0, Name = "- Please Select -" });
// Add this line
// Make sure you use the correct ID for the "Other" subject
subjects.Add(new Subject() { ID = 100, Name = "Other" });
// If you determine the ID based on the list, simply set the ID = subjects.Count + 1
int otherID = subjects.Count + 1;
subjects.Add(new Subject() { ID = otherID, Name = "Other" });
ViewData["Subjects"] = subjects;
}