Note that there are some explanatory texts on larger screens.

plurals
  1. PODropdownListFor - Null Reference Exception on page model
    primarykey
    data
    text
    <p>I'm trying to save one of my Models to the database. Given the models:</p> <pre><code>public class Foo { public int Id { get; set; } public string Name { get; set; } public virtual Bar Something { get; set; } } public class Bar { public int Id { get; set; } public string Name { get; set; } } public class FooPageModel { public Foo F { get; set; } public List&lt;SelectListItem&gt; Bars { get; set; } } </code></pre> <p>In my controller I have:</p> <pre><code>public ActionResult Add(){ var bars = ... // get all bars from db context var barsList = new List&lt;SelectListItem&gt;(); barsList.AddRange(bars.Select(b =&gt; new SelectListItem { Text = b.Name, Value = b.Name })); var model = new FooPageModel { Bars = barsList }; return View("Add", model); } </code></pre> <p>Now for the View (strongly typed to FooPageModel):</p> <pre><code>&lt;%: Html.DropdownListFor(f =&gt; f.F.Bar, Model.Bars) %&gt; </code></pre> <p>The view renders fine, with the values I expect, but when I submit the page form, I get a NullReferenceException (on the view line pasted above before the action on the controller is ever reached). I thought maybe if I modified my controller code to:</p> <pre><code>var model = new FooPageModel { F = new Foo(), Bars = barsList } </code></pre> <p>However, this fails as well. I suppose I could re-write FooPageModel to just be a list of strings of the information I want, but it seems redundant to duplicate Model logic; I'm pretty new to CTP in general, so maybe that's how it's done?</p> <p>I was able to code up something similar for a ComplexType (an address Model) and had no problems. If the stack trace would be helpful, let me know and I'll post it. Thanks in advance.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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