Question

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?

Was it helpful?

Solution

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top