Note that there are some explanatory texts on larger screens.

plurals
  1. PODropDownList Result not being Returned
    text
    copied!<p>I am trying to create an Item that has an ItemType coming from another table. I am unable to get back the actual Type object from the Create page. This is the code I have tried:</p> <p>Models:</p> <pre><code>public class ItemType { public int Id { get; set; } [Required] public string Name { get; set; } public virtual ICollection&lt;Item&gt; Item{ get; set; } } public class Item { public int Id { get; set; } [Required] public string Name { get; set; } public virtual ItemType ItemType { get; set; } } </code></pre> <p>In the ItemController, this is my create code:</p> <pre><code> public ActionResult Create() { var itemTypeRepo = new ItemTypeRepository(context); ViewBag.ItemTypes = new SelectList(itemTypeRepo.GetAll(), "ID", "Name"); return View(); } [HttpPost] public ActionResult Create(Item item) { if (ModelState.IsValid) { context.Items.Add(item); context.SaveChanges(); return RedirectToAction("Index"); } return View(item); } </code></pre> <p>In my Create.cshtml view I have tried:</p> <pre><code>&lt;div class="editor-field"&gt; @Html.DropDownList("ItemType", String.Empty) @Html.ValidationMessageFor(model =&gt; model.ItemType) &lt;/div&gt; </code></pre> <p>This returns no value at all and throws an error "The value 'X' is invalid." Where X is the ID of the ItemType I selected. And</p> <pre><code>&lt;div class="editor-field"&gt; @Html.DropDownListFor(x =&gt; x.ItemType.Id, (SelectList)ViewBag.ItemType) @Html.ValidationMessageFor(model =&gt; model.ItemType) &lt;/div&gt; </code></pre> <p>This creates a stub ItemType object with the correct ID but does not insert it into the database since the object is not fully loaded. If I look at ModelState object, I find that there is an error that the Name field is missing from ItemType object.</p> <p>I also attempted to solve the problem using the second .cshtml code and adding this code:</p> <pre><code>public ActionResult Create(Item item) { item.ItemType = context.ItemTypes.Find(item.ItemType.Id); if (ModelState.IsValid) </code></pre> <p>This does not change the value of ModelState.IsValid from false even through it should.</p> <p>What do I need to do to get this to work?</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