Note that there are some explanatory texts on larger screens.

plurals
  1. POASP.NET MVC 2 - Html.DropDownListFor confusion with ViewModel
    text
    copied!<p>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</p> <p>In the View I'm writting:</p> <pre><code>&lt;%= Html.DropDownListFor(m =&gt; m.ParentCategory, new SelectList(Model.Categories, "CategoryId", "Name", Model.ParentCategory), "[ None ]")%&gt; &lt;%= Html.ValidationMessageFor(m =&gt; m.ParentCategory)%&gt; </code></pre> <p>and my Model object is thus:</p> <pre><code>public class CategoryForm : FormModelBase { public CategoryForm() { Categories = new List&lt;Category&gt;(); 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&lt;Category&gt; Categories { get; protected set; } public class Category { public int? CategoryId { get; set; } public string Name { get; set; } } } </code></pre> <p>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."</p> <p>So I change the View to...</p> <pre><code>&lt;%= Html.DropDownListFor(m =&gt; m.ParentCategory.**CategoryId**, new SelectList .../ snip ) %&gt; </code></pre> <p>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?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload