我想爲我的稱爲Product的Linq2SQL實體實現一個Edit ViewModel。它有一個外鍵鏈接到品牌列表。在ASP.NET MVC2中使用SelectList綁定的ViewModel
目前我通過填充ViewData的品牌列表,並使用DropDownListFor,即:
<div class="editor-field">
<%= Html.DropDownListFor(model => model.BrandId, (SelectList)ViewData["Brands"])%>
<%= Html.ValidationMessageFor(model => model.BrandId) %>
</div>
現在我想重構視圖中使用強類型的視圖模型和Html.EditorForModel():
<% using (Html.BeginForm()) {%>
<%= Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<%=Html.EditorForModel() %>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
在我的編輯視圖模型,我有以下幾點:
public class EditProductViewModel
{
[HiddenInput]
public int ProductId { get; set; }
[Required()]
[StringLength(200)]
public string Name { get; set; }
[Required()]
[DataType(DataType.Html)]
public string Description { get; set; }
public IEnumerable<SelectListItem> Brands { get; set; }
public int BrandId { get; set; }
public EditProductViewModel(Product product, IEnumerable<SelectListItem> brands)
{
this.ProductId = product.ProductId;
this.Name = product.Name;
this.Description = product.Description;
this.Brands = brands;
this.BrandId = product.BrandId;
}
}
的CON troller是設置像這樣:
public ActionResult Edit(int id)
{
BrandRepository br = new BrandRepository();
Product p = _ProductRepository.Get(id);
IEnumerable<SelectListItem> brands = br.GetAll().ToList().ToSelectListItems(p.BrandId);
EditProductViewModel model = new EditProductViewModel(p, brands);
return View("Edit", model);
}
產品ID,名稱和描述在正確生成的視圖顯示,但是選擇列表沒有。品牌列表中包含數據。
如果我這樣做,我認爲,選擇列表的可見:
<% using (Html.BeginForm()) {%>
<%= Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<%=Html.EditorForModel() %>
<div class="editor-label">
<%= Html.LabelFor(model => model.BrandId) %>
</div>
<div class="editor-field">
<%= Html.DropDownListFor(model => model.BrandId, Model.Brands)%>
<%= Html.ValidationMessageFor(model => model.BrandId) %>
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
我在做什麼錯? EditorForModel()不一般支持SelectList嗎?我是否缺少某種DataAnnotation?
我似乎無法找到ViewModels中的SelectList用法的任何示例幫助。我真的很難過。 This answer似乎接近,但沒有幫助。
看起來像下一個版本可能支持我在找什麼:http://aspalliance.com/1687_ASPNET_MVC_Preview_3_Release.3 – Junto 2010-05-06 06:56:27