3

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

目前仅使用 Units.Name 填充,但我还想使用其 Unit.Id 填充它(将在下拉列表中隐藏),以便在用户选择项目时获取 ID 并在单击创建按钮时使用它(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>

提前致谢!

4

2 回答 2

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");
于 2013-03-12T09:58:00.507 回答
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...
                      };
于 2013-03-12T09:55:12.180 回答