我正在尝试选择多个值,并将它们分配给具有特定选项/值的选择列表,然后将其通过viewbag传递到我的视图,该结构在渲染时以及处于编辑模式时都存在问题该值未预先填充。
我已经进行了各种搜索以了解这一点,但是大多数都使用JQuery或其他框架,我希望保留在C#/ MVC中,只是我现在不确定要查找哪个短语才能找到现有的短语解决这类问题。
有人可以给我一些建议吗?
查看:
<div class="form-group">
@Html.LabelFor(model => model.employeeID, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.employeeID, ViewBag.employee as List<SelectListItem>, "Select", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.employeeID, "", new { @class = "text-danger" })
</div>
</div>
控制器:
var employeeID = ((from x in dbdev.employeeDetails orderby x.employeeID select new { Name = x.employeeNumber + x.knownas + x.surname, Value = x.employeeID } ).Distinct()).ToList();
SelectList employeeIDList = new SelectList(employeeID);
ViewBag.employeeID = employeeIDList;
型号:
[Required]
[Range(1, 2147483647)]
[Display(Name = "Employee ID")]
public int employeeID { get; set; }
呈现我的代码后,select具有以下结构
<option>{ Name = 568883PhilShort, Value = 1 }</option>
但是我实际上正在尝试产生以下结构。
<option value="1">568883 Phil Short</option>
以下是修改后的评论
模型/ HTML不变
根据评论更新了控制器:
var employeesList = (from x in dbdev.employeeDetails.AsEnumerable()
orderby x.employeeID ascending
select new
{
Name = String.Format("{0} {1} {2}", x.employeeNumber, x.knownas, x.surname),
Value = x.employeeID
}).ToList();
SelectList employeeIDList = new SelectList(employeesList, "Value", "Name", userAccess.employeeID);
ViewBag.employeeID = employeeIDList;
然后将我重构的代码减少到以下内容:
ViewBag.employeeID = new SelectList((from x in dbdev.employeeDetails.AsEnumerable()
orderby x.employeeID ascending
select new
{
Name = String.Format("{0} {1} {2}", x.employeeNumber, x.knownas, x.surname),
Value = x.employeeID
}).ToList(), "Value", "Name", userAccess.employeeID);
答案 0 :(得分:2)
您只需要进行一些纠正,使代码看起来像这样:
var employeesList = dbdev.employeeDetails.OrderBy(x => x.employeeID)
.AsEnumerable()
.Select(x => new {
Name = String.Format("{0} {1} {2}", x.employeeNumber, x.knownas, x.surname),
Value = x.employeeID
}).ToList();
使用查询表达式的替代方法:
var employeesList = (from x in dbdev.employeeDetails.AsEnumerable()
orderby x.employeeID ascending
select new {
Name = String.Format("{0} {1} {2}", x.employeeNumber, x.knownas, x.surname),
Value = x.employeeID
}).ToList();
然后使用现有列表创建一个SelectList
:
SelectList employeeIDList = new SelectList(employeesList, "Value", "Name", userAccess.employeeID);
或者...直接创建一个IEnumerable<SelectListItem>
并将其传递给DropDownListFor
助手:
var employeesList = dbdev.employeeDetails.OrderBy(x => x.employeeID)
.AsEnumerable()
.Select(x => new SelectListItem {
Text = String.Format("{0} {1} {2}", x.employeeNumber, x.knownas, x.surname),
Value = x.employeeID
}).ToList();