tôi nhận được hoàn toàn bị mất và lẫn lộn về cách sử dụng mạnh mẽ gõ Html.DropDownListFor helper mới về ASP.NET MVC 2.0 R2ASP.NET MVC 2 - Html.DropDownListFor nhầm lẫn với ViewModel
Trong Xem tôi 'm writting:
<%= Html.DropDownListFor(m => m.ParentCategory, new SelectList(Model.Categories, "CategoryId", "Name", Model.ParentCategory), "[ None ]")%>
<%= Html.ValidationMessageFor(m => m.ParentCategory)%>
và đối tượng mẫu của tôi là như sau:
public class CategoryForm : FormModelBase
{
public CategoryForm()
{
Categories = new List<Category>();
Categories.Add(new CategoryForm.Category() {
CategoryId = 1,
Name = "CPUs" });
Categories.Add(new CategoryForm.Category() {
CategoryId = 2,
Name = "Memory" });
Categories.Add(new CategoryForm.Category() {
CategoryId = 3,
Name = "Hard drives" });
}
// ...other props, snip... //
public Category ParentCategory { get; set; }
public IList<Category> Categories { get; protected set; }
public class Category
{
public int? CategoryId { get; set; }
public string Name { get; set; }
}
}
vấn đề là khi tôi chọn một mục từ danh sách thả xuống, nói mục đầu tiên, tôi nhận được Valida sau Lỗi tionMessageFor "Giá trị '1' không hợp lệ."
Vì vậy, tôi thay đổi Xem để ...
<%= Html.DropDownListFor(m => m.ParentCategory.**CategoryId**,
new SelectList .../ snip ) %>
Bây giờ nó hoạt động, kinda. Thuộc tính ParentCategory trong ViewModel của tôi được đặt với 'CategoryId' chính xác nhưng 'Name' là NULL. Tôi có tốt hơn off chỉ có một int nullable cho ParentCategory bất động sản thay vì một mạnh mẽ gõ 'Thể loại' đối tượng?
Đây là một cách tốt để người dùng DropDownListFor - http://stackoverflow.com/questions/3386998/dropdownlistfor-display-a-simple-list-of-strings – bcahill