0

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

4

2 回答 2

2

当您返回时,ClassOne您需要将classTwoObject属性初始化为new ClassTwo()

- 就像上面提到的布鲁克。打败我。

于 2012-10-22T17:50:44.387 回答
1

您可以创建一个初始化 classTwoObject 的构造函数

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

}

或者只是内联初始化它

new ClassOne(){classTwoObject=new ClassTwo()};
于 2012-10-22T17:53:27.637 回答