DropdownListFor - 页面模型上的空引用异常
我正在尝试将我的模型之一保存到数据库中。给定模型:
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; }
}
在我的控制器中,我有:
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);
}
现在对于视图(强类型化为 FooPageModel):
<%: Html.DropdownListFor(f => f.F.Bar, Model.Bars) %>
视图呈现良好,具有我期望的值,但是当我提交页面表单时,我得到一个 NullReferenceException (在粘贴的视图行上)在达到控制器上的操作之前)。我想也许如果我将控制器代码修改为:
var model = new FooPageModel
{
F = new Foo(),
Bars = barsList
}
但是,这也失败了。我想我可以将 FooPageModel 重写为我想要的信息的字符串列表,但重复模型逻辑似乎是多余的;总的来说,我对 CTP 还很陌生,所以也许这就是它的工作原理?
我能够为 ComplexType(地址模型)编写类似的代码,并且没有任何问题。如果堆栈跟踪有帮助,请告诉我,我会发布它。提前致谢。
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 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:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有显示返回
ActionResult
的代码,但您需要确保将模型传递给视图,如下所示: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: