How to instantiate a class if its properties are not primitive types?

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

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

In terms of the functionality that I use, I created another class ( MyData strong>), whose property elements are of type MyDataInfo.

2) Here MyData p>

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

3) And here is my method of action

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

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

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

Unfortunately, I got an error " The object is not installed in the object instance ."

Am I missing something or is there another way to get the same result?

+3
source share
1 answer

MyData, Prop1 Prop2, (Prop1 null, Model.Prop1.Name ). :

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

MyData:

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

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

Source: https://habr.com/ru/post/1741645/


All Articles