2015-07-04 29 views
1

我的模型和控制器有一个愚蠢的问题。 我想用部分视图在一个视图上显示两个模型。未设置ASP.NET MVC对象引用(为模型添加值)

当我在控制器中填充模型我得到这个消息对象引用没有设置.. 但我不知道为什么?

这里是我的控制器和模型:

控制器:

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); 
} 

型号:

namespace MVCPArtial.Models 
{ 
    public class ChartItem 
    { 
     public string Name { get; set; } 
    } 
} 

型号:

namespace MVCPArtial.Models 
{ 
    public class ListItem 
    { 
     public string Name { get; set; } 
    } 
} 

型号:

namespace MVCPArtial.Models 
{ 
    public class MultiModel 
    { 
     public List<ChartItem> ChartItems { get; set; } 
     public List<ListItem> ListItems { get; set; } 
    } 

} 

错误:enter image description here

回答

3

您还没有MultiModel初始化集合。无论是添加默认的构造函数

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; } 
} 

还是在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); 
+0

大泉,谢谢你很多! – Nezir

相关问题