MVC3使用值和名称填充下拉列表

时间:2013-03-12 09:51:00

标签: asp.net-mvc asp.net-mvc-3 http-post html-select

使用MVC3。我已经有一个 DropDownList 从数据库表中填充

目前只使用Units.Name填充,但是我想用它的Unit.Id(它将隐藏在下拉列表中)填充它,以便在用户选择项目时获取ID并在它们clic时使用它在“创建”按钮上(POST方法)。

我需要修改什么才能让它以这种方式运作?

我知道这是微不足道的,但我是MVC的新手。我尝试了很多可能性但没有成功。

...控制器

public ActionResult Create()
{

private BridgeEntities db = new BridgeEntities();


    var query = (from units in db.Units
                 select units).ToList().OrderBy(q => q.Name);

    List<string> listOfUnits = new List<string>();
    foreach (var item in query)
    {
        listOfUnits.Add(item.Name);
    }
    ViewBag.ListOfUnits = listOfUnits;


    return View();
} 

在创建视图中......

@Html.DropDownList("Unit",new SelectList(ViewBag.ListOfUnits))

我的创建按钮...

<button type="submit" class = "btn btn-success">
    <i class="icon-plus icon-white"></i> Create
</button>

提前致谢!

2 个答案:

答案 0 :(得分:3)

ViewBag.ListOfUnits = new SelectList(db.Units.OrderBy(q => q.Name).ToList(), 
                                         "Id", 
                                         "Name");

更新:

脱离我的头顶:

// Select Ids to exclude from list
IQueryable<int> exclude = db.DeprecatedUnits.Select(p => p.UnitID);

// Select units for selectlist, ignore the ids which are in exclude list
var units = db.Units.Where(q => !exclude.Contains(q.Id)).OrderBy(q => q.Name).ToList();

// Create the selectlist
ViewBag.ListOfUnits = new SelectList(units,"Id","Name");

答案 1 :(得分:1)

ViewBag.ListOfUnits = (from units in db.Units select units)
                      .ToList().OrderBy(q => q.Name)
                      .Select(s => new SelectListItem 
                      { 
                          Text = s.Name, 
                          Value = s.Id// or s.ID , what property does your model have...
                      };