我想让我的模型与ASP.NET MVC 5中的Identity系统中的用户相关联,而不是 Employee 。我的问题是,我似乎无法弄清楚@ Html.DropDownList背后的魔力......我正在拉我的头发。这是我的ViewModel:
public class TicketViewModel
{
[Display(Name="ID#")]
public int TicketId { get; set; }
public int EmployeeId { get; set; }
public int ShopId { get; set; }
public int UserId { get; set; }
public int ApplicationUserId { get; set; }
public string Description { get; set; }
public string Status { get; set; }
public EmployeeViewModel Employee { get; set; }
public ShopViewModel Shop { get; set; }
public TotsUser User { get; set; }
}
和TicketController方法:
// GET: /Ticket/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Ticket ticket = db.Tickets.Find(id);
if (ticket == null)
{
return HttpNotFound();
}
TicketViewModel ticketVM = Mapper.Map(ticket, new TicketViewModel());
ViewBag.EmployeeId = new SelectList(db.Employees, "EmployeeId", "Name", ticketVM.EmployeeId);
ViewBag.ShopId = new SelectList(db.Shops, "ShopId", "Name", ticketVM.ShopId);
ViewBag.UserListing = new SelectList(db.Users, "Id", "UserName", ticketVM.UserId);
return View(ticketVM);
}
视图(有问题的部分)
<div class="form-group">
@Html.LabelFor(model => model.EmployeeId, "EmployeeId", new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("EmployeeId", String.Empty)
@Html.ValidationMessageFor(model => model.EmployeeId)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.UserId, "UserId", new { @class = "control-label col-md-2" })
<div class="col-md-10">
@* @Html.DropDownList("UserId", String.Empty) *@
@Html.DropDownList("UserId", @ViewBag.UserListing, null);
@Html.ValidationMessageFor(model => model.UserId)
</div>
</div>
我甚至无法解释它如何与 EmployeeId 一起使用。这是脚手架为我的原始模型生成它的方式。它填充EmployeeId
就好了。有人可以解释一下使用@Html.DropDownList
助手进行的黑暗魔法并解释为什么我不能让DropDownList填充任何东西吗?
答案 0 :(得分:0)
您可以尝试更改
ViewBag.UserListing = new SelectList(db.Users, "Id", "UserName", ticketVM.UserId);
到
ViewBag.UserId = new SelectList(db.Users, "Id", "UserName", ticketVM.UserId);
或更改
@Html.DropDownList("UserId", @ViewBag.UserListing, null);
到
@Html.DropDownList("UserId", (SelectList)@ViewBag.UserListing);
无论您使用哪种方法
,这都是错误的 @Html.DropDownList("UserId", @ViewBag.UserListing, null);
你必须告诉助手什么类型的对象@ViewBag.UserListing
。在您的情况下,它将是(SelectList)@ViewBag.UserListing