开发者

DropdownListFor - Null Reference Exception on page model

开发者 https://www.devze.com 2023-02-14 07:06 出处:网络
I\'m trying to save one of my Models to the database.Given the models: public class Foo { public int Id { get; set; }

I'm trying to save one of my Models to the database. Given the models:

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<SelectListItem> Bars { get; set; }
}

In my controller I have:

public ActionResult Add(){
     var bars = ... // get all bars from db context
     var barsList = new List<SelectListItem>();
     barsList.AddRange(bars.Select(b => new SelectListItem {
          Text = b.Name,
          Value = b.Name
     }));

     var model = new FooPageModel
     {
          Bars = barsList
     };
     return View("Add", model);
 }

Now for the View (strongly typed to FooPageModel):

<%: Html.DropdownListFor(f => f.F.Bar, Model.Bars) %>

The view renders fine, with the values I 开发者_如何学Cexpect, 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:

var model = new FooPageModel
{
     F = new Foo(),
     Bars = barsList
}

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?

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.


You aren't showing the code where you return the ActionResult, but you need to make sure you are passing the model to the view, like this:

public ActionResult Add() {
    ...

    return View(model);  // send the model to the view
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号