views:

442

answers:

2

I have a 'Person' object that has a 'FirstName' and '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?

+1  A: 

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?

griegs
Yes this seems to be correct, as you are creating an Person object, you are also creating a Null Phone object until it is populated as above.
Nicholas Murray
You could even choose to add the code that creates and adds this first Phone object `pp` to your constructor/Class Initialize... This way, anytime you instantiate a New Person, you'll know this first Phone reference will always be there for you.
Funka
I said that! But not quite so clearly! :)
griegs
Thanks, I thought SingleOrDefault() would create a new object if there was no match. I now changed my Perosn constructor like Funka proposed.
Stief Dirckx
A: 

I tried the example, in the view the phone number shows up, but when I change it and post, only the person object returned to the server, the list of phone numbers became Null.

Does the proposed solution works for anybody?

Gabrile
This is not an answer. It's a question on top of the question or to some other answer. This "answer" should be added as a comment where it belongs.
Robert Koritnik
I apologize, you right, but unfortunately didn't see the comment link.Sorry
Gabrile