创建构造函数并发送到视图

时间:2014-06-10 12:09:50

标签: c# asp.net-mvc ravendb

我为我的狗创造了一个血统树,我有麻烦。 我有三个班级:

狗班:

 public class Dog
    {
        public string Name { get; set; }
        public string Merit1 { get; set; }
        public string Merit2 { get; set; }           
    }

谱系课程:

 public class Pedigree
    {
        public Dog Father { get; set; }
        public Dog GrandFather { get; set; }
        public Dog GrandMother { get; set; }
        public Dog GrandFathersFather { get; set; }
        etc....

我想要发送到视图的类,这里带有编码值,只是为了让我开始:

public class DogContentPage : ContentPage
    {

        public DogContentPage()
        {
            Name = "The Dog";
            Age = "4";


            Pedigree = new Pedigree();
            {

                mother = new Dog {Name = "Chanelle", Merit1 = "Universal"};
                father = new Dog {Name = "dfdfdf", Merit1 = "dfdfdfdfdf"};

            };

        }

        public string Name { get; set; }
        public string Age { get; set; }
        public Dog mother { get; set; }
        public Dog father { get; set; }  
    }

在视图中我尝试这样简单的事情:

    @model EmmysBlog_Core.Models.Dog.DogContentPage

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>@Model.Name</h1>

<p>@Model.Pedigree.Mother.Name</p>
<p>@Model.Pedigree.Mother.Merit1</p>

我得到的错误是,对象未设置为实例... 我想要的是能够显示我的狗的属性......我缺少什么?

1 个答案:

答案 0 :(得分:1)

Pedigree构造函数中,您还需要实例化属性类,它们不会实例化,因此会抛出 null引用异常

public Pedigree()
{
    this.Mother = new Dog{Name = "Chanelle", Merit1 = "Universal"};
    this.Father = new Dog{Name = "dfdfdf", Merit1 = "dfdfdfdfdf"};
    this.GrandFather = new Dog();
    this.GrandMother = new Dog();
    this.GrandFathersFather = new Dog();
}

在你的代码中也有错误,你的方式应该是这样的:

Pedigree obj = new Pedigree
{
    Mother = new Dog {Name = "Chanelle", Merit1 = "Universal"};
    Father = new Dog {Name = "dfdfdf", Merit1 = "dfdfdfdfdf"};
};