I'm getting totally lost and confused on how to use the new strongly typed Html.DropDownListFor helper on ASP.NET MVC 2.0 R2
In the View I'm writting:
<%= Html.DropDownListFor(m => m.ParentCategory, new SelectList(Model.Categories, "CategoryId", "Name", Model.ParentCategory), "[ None ]")%>
<%= Html.ValidationMessageFor(m => m.ParentCategory)%>
and my Model object is thus:
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; }
}
}
The problem is that when I select an item from the dropdown list, say the first item, I get the following ValidationMessageFor error "The value '1' is invalid."
So I change the View to...
<%= Html.DropDownListFor(m => m.ParentCategory.**CategoryId**,
new SelectList .../ snip ) %>
Now it works, kinda. The ParentCategory property in my ViewModel is set with the correct 'CategoryId' but the 'Name' is NULL. Am I better off just having a nullable int for ParentCategory property instead of a strongly typed 'Category' object?