我正在顯示用戶列表。每個用戶記錄都有一個TrainingEvent對象屬性(來自多個TrainingEvent的選擇)。我創建了一個視圖模型來包含用戶列表和TrainingEvents列表。MVC3 DropDownListFor未選擇保存的值
視圖模型:
public class RegistrationViewModel
{
public IEnumerable<Domain.Entities.User> Users { get; set; }
public IEnumerable<SelectListItem> TrainingEvents { get; set; }
}
(注意:Domain.Entities.User包含TrainingEvent對象屬性)
控制器:
public ActionResult Dealership(int id)
{
var model = new RegistrationViewModel
{
Users = repository.Find
.Where(u => u.Dealer.DealerId == id).OrderBy(u => u.LastName),
TrainingEvents = repository.TrainingEvents.ToList()
.Select(x => new SelectListItem
{
Text = x.Date.ToString() + " - " + x.LocationName,
Value = x.TrainingEventId.ToString()
})
};
return View("East", model);
}
結合在爭奪瓦特:
@foreach(Company.Domain.Entities.User usr in Model.Users)
{
<tr>
<td>@usr.LastName</td>
<td>@usr.FirstName</td>
<td>@usr.JobDescription</td>
<td>@Html.DropDownListFor(m => m.Users.FirstOrDefault(u => u.UserId == usr.UserId).TrainingEvent, Model.TrainingEvents)</td>
</tr>
}
在使用者列,並且每個用戶行具有與TrainingEvents填充下拉。但是,以前保存在用戶的TrainingEvent對象中的值未被選中。任何想法,爲什麼不呢?