[英]ASP.NET MVC Object reference not set ( adding value to model)
I have stupid problem with my model and controller. 我的模型和控制器有愚蠢的问题。 I am trying to show two models on one view with Partial Views.
我试图在一个视图上使用部分视图显示两个模型。
When I fill model in controller I getting this message Object reference not set.. But I am not sure why? 当我在控制器中填充模型时,我收到此消息对象引用未设置..但我不知道为什么?
Here is my controller and models: 这是我的控制器和型号:
Controller: 控制器:
public ActionResult MultiView()
{
ChartItem c = new ChartItem();
c.Name = "Chart";
ChartItem c1 = new ChartItem();
c1.Name = "Chart1";
List<ChartItem> a = new List<ChartItem>();
a.Add(c);
a.Add(c1);
ListItem l = new ListItem();
l.Name = "List";
ListItem l1 = new ListItem();
l1.Name = "List1";
List<ListItem> b = new List<ListItem>();
b.Add(l);
b.Add(l1);
MultiModel m = new MultiModel();
m.ChartItems.Add(c);
m.ListItems.AddRange(b);
List<MultiModel> model = new List<MultiModel>();
model.Add(m);
return View(model);
}
Model: 模型:
namespace MVCPArtial.Models
{
public class ChartItem
{
public string Name { get; set; }
}
}
Model: 模型:
namespace MVCPArtial.Models
{
public class ListItem
{
public string Name { get; set; }
}
}
Model: 模型:
namespace MVCPArtial.Models
{
public class MultiModel
{
public List<ChartItem> ChartItems { get; set; }
public List<ListItem> ListItems { get; set; }
}
}
Error: 错误:
You have not initialized the collections in MultiModel
. 您尚未在
MultiModel
初始化集合。 Either add a default constructor 添加默认构造函数
public class MultiModel
{
// add parameterless constructor
public MultiModel()
{
ChartItems = new List<ChartItem>();
ListItems = new List<ListItem>)();
}
public List<ChartItem> ChartItems { get; set; }
public List<ListItem> ListItems { get; set; }
}
Or in the MultiView()
method, initialize the collections 或者在
MultiView()
方法中,初始化集合
MultiModel m = new MultiModel();
m.ChartItems = new List<ChartItem>(); // add this
m.ListItems = new List<ListItem>)(); // add this
m.ChartItems.Add(c);
m.ListItems.AddRange(b);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.