【问题标题】:Combining multiple models in one view在一个视图中组合多个模型
【发布时间】:2012-09-19 07:34:27
【问题描述】:

我对此处给出的已接受答案有一个后续问题:Two models in one view in ASP MVC 3

我想在一个视图中列出三个模型,类型、原因、位置。根据上面链接中的答案,我制作了一个新模型,它结合了如下所示:

public class Combined
    {
        public IEnumerable<Place> Place { get; set; }
        public IEnumerable<Type> Type { get; set; }
        public IEnumerable<Cause> Cause { get; set; }
    }

我将其设为 IEnumerable 因为据我了解,当我只想在 foreach 循环中列出这些模型的内容时,这就是我想要的。然后我为视图制作了这个控制器:

[ChildActionOnly]
    public ActionResult overSightHeadings()
    {
        Combined Combined = new Combined();
        return View(Combined);
    }

最后是视图(我只是想先从其中一个表中列出):

@model mvcAvvikelser.Models.Combined
@{
    Layout = null;
}
<tr>
@foreach (var Type in Model.Type)
{
    <th> @Html.DisplayTextFor(ModelItem => Type.Name)</th>
}
</tr>

这段代码的问题是它在 foreach 代码启动时抛出了一个空异常。

System.NullReferenceException: Object reference not set to an instance of an object.

所以我不完全确定我在这里做错了什么,它应该不是 IEnumerable,我是否在控制器中错误地初始化了模型?

【问题讨论】:

  • 你做错了什么是你没有初始化你的 Combined 属性。列表为空

标签: asp.net-mvc-3


【解决方案1】:

应该是这个

[ChildActionOnly]
public ActionResult overSightHeadings()
{
    Combined combined = new Combined();
    combined.Types = new List<Type>();
    combined.Causes = new List<Cause>();
    combined.Places = new List<Place>();

    return View(Combined);
}

请注意,我已将属性名称更改为复数。这将您的财产定义为收藏。

【讨论】:

  • 谢谢,这似乎有效,至少不会引发错误。不过,该视图似乎没有返回任何结果。
  • 你需要给它们赋值。现在它们是空的。你从哪里得到这些值?获取这些值并分配它们而不是 new List&lt;Type&gt;()
  • 啊,当然。现在你解释了它是有道理的。我从数据库中检索值,并将新的 List() 替换为正确的“连接”,现在它可以正常工作:)
【解决方案2】:

看起来像

 public IEnumerable<Type> Type { get; set; }

未设置

尝试在模型构造函数中初始化这个列表 没有 IEnumerable 喜欢

 List<Type> Type = new List<Type>();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    • 2012-03-31
    • 1970-01-01
    相关资源
    最近更新 更多