Вопрос

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

Это было полезно?

Решение

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()};

Другие советы

When you return back your ClassOne you need to initialize the classTwoObject property to a new ClassTwo()

-Like Brook mentioned above. Beat me to it.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top