Search code examples
asp.net-mvcrazornullhtml.textboxfor

MVC - null object in model, how do I render textboxfor with this


how do I render a textbox using textboxfor in MVC when I have a null class in the model.

For example I have the following I am using as my model

public class ClassOne
{
    public string classOneProperty {get;set;}
    public ClassTwo classTwoObject {get; set;}
}

public class ClassTwo
{
    public string classTwoProperty {get;set;}
}

So I have a table of class one values and the user clicks to edit an existing item of ClassOne. In ClassOne the object ClassTwo is null since it wasnt set at the initial creation of the item in the table, so when i try to do @Html.TextBoxFor(m => m.classTwoObject.classTwoProperty) I get a null reference error.

How can I use the TextBoxFor to edit fields that have null objects in them since I still want them to bind to the model on postback?

Thanks, DMan


Solution

  • You can create a constructor that initializes classTwoObject

    public class ClassOne
    {
        public string classOneProperty {get;set;}
        public ClassTwo classTwoObject {get; set;}
        public CLassOne()
        {
            classTwoObject = new ClassTwo();
        }
    
    }
    

    Or just initialize it inline

    new ClassOne(){classTwoObject=new ClassTwo()};