如何将数字绑定到数据库的Dropdownlist中

时间:2015-04-21 08:51:30

标签: asp.net asp.net-mvc-4

如何将数字绑定到数据库的Dropdownlist中? (我想绑定10,20,30 .....到2000年之后,我的要求可能会改为5,10,15,20--2000,) 我在数据库中有一个列应该绑定到dropdownlist需要一个通用逻辑来绑定dropdownlist项  请帮我解决这个问题...

1 个答案:

答案 0 :(得分:0)

创建模型:

public class myViewModel{
    public int selectedIndex { get; set; } //one for selected index
    public List<myItemsModel> mylist { get; set; } // one for list
}

填充模型:

public ActionResult myView() {
    myViewModel model = new myViewModel();
    model.selectedIndex  = aninteger;
    model.mylist = (from blah in blahblah .....);
    return View(model);
}

在您看来:

//Bind the model
@model myProject.Models.myViewModel

//Bind the 2 view models to the control
@Html.DropDownListFor(x => x.selectedIndex , new SelectList(Model.mylist, "id", "dt", Model.selectedIndex), "Placeholder", new { onchange = @"this.form.submit();", @class = "your css class" })