简体   繁体   中英

How to instantiate a class when its property members are not of primitive types?

1) Let's say I've a class MyDataInfo:

public class MyDataInfo
{
  public int MyDataInfoID { get; set; }
  public string Name { get; set; }
}

For the purpose of the functionality I'm after, I've created another class ( MyData ) whose property members are of MyDataInfo type.

2) Here's MyData

public class MyData
{
  public MyDataInfo Prop1 { get; set; }
  public MyDataInfo Prop2 { get; set; }
}

3) And, here's my action method

public ActionResult MyAction()
{
  MyData myObject = new MyData();
  return View(myObject);
}

4) Finally, this in my View template (which is strongly typed and inherits from MyData )

<%= Html.Encode (Model.Prop1.Name) %>
<%= Html.Encode (Model.Prop2.Name) %>

Unfortunately, I got an error " Object not set to an instance of an object ."

Am I missing something or is there a different way of obtaining the same result?

You've instantiated MyData , but not Prop1 and Prop2 which you are trying to access in the view ( Prop1 is null, so Model.Prop1.Name will throw an exception). You will need to instantiate these properties:

public ActionResult MyAction()
{
    var myObject = new MyData 
    {
        Prop1 = new MyDataInfo(),
        Prop2 = new MyDataInfo()
    };
    return View(myObject);
}

This could also be done in the constructor of MyData:

public class MyData
{
    public void MyData()
    {
        Prop1 = new MyDataInfo();
        Prop2 = new MyDataInfo();
    }

    public MyDataInfo Prop1 { get; set; }
    public MyDataInfo Prop2 { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM