开发者

ASP.NET MVC Create view for object with first child object

I have a 'Person' object that has a 'FirstName' and 开发者_Go百科'LastName' property. The 'Person' also has a 1-n relation with a 'Phone' object. The 'Phone' object has a 'Number' property. So a person can have multiple phone numbers.

On the 'PersonController' I have a 'Create' action that loads a strongly-typed view to show a form where I can create a new 'Person'. But besides the person's properties I also want to be able to enter a first phone child object.

This codes gives me a NullReferenceException:

Html.TextBox("Number", Model.Person.Phones.SingleOrDefault().Number)

In my action method I call the view like this:

Dim p As New Person
Return View(p)

So how can I create an object and a first child object on a single view?


Isn't it because the phone number object hasn't been set and is in actual fact null?

So when you create a new person you would also need to create a new phone number object.

erm like like this I (think) and my VB is rusty;

Dim p as New person
Dim pp as new Phones
p.Phones.Add (pp)
return View(p)

So in essense when you create a new person a new phone needs to be created and attached to the new person.

You could do this better by refactoring the above code into the create of the Person object so that there is always a new Phone object attached to a new Person.

Does this make sense or am I off base?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜