Good day everybody,
I’m having troubles with the display of a data that does not always exist.
<div class="display-label">client</div>
<div class="display-field">
@Model.Contact.client.nomCompteClient
</div>
<div class="display-label">civilite</div>
<div class="display-field">
@Model.Contact.civilite
</div>
In this code, if @Model.Contact.client.nomCompteClient is not set, I get the following error : Object reference not set to an instance of an object.
But, if every other data is empty, there is no problem, there is just nothing that is displayed.
I don’t understand what I’ve done to set “nomCompteClient” mandatory.
here is my controller :
Function Details(id As Integer) As ActionResult
Dim contact As contact = db.contact.Single(Function(c) c.idContact = id)
Dim meetings = (From d In db.meeting
Where d.FK_meet_contact = id
Select d).ToList()
Dim opportunites = (From e In db.opportunite
From f In db.transmission_opportunite
Where f.FK_trans_cont = id And f.FK_trans_opp = e.idOpportunite
Select e).ToList()
Dim interviews = (From g In db.interview
Where g.FK_int_contact = id
Select g).ToList()
Dim model = New ContactDetails With {
.Contact = contact,
.Meetings = meetings,
.Interviews = interviews,
.Opportunites = opportunites
}
Return View(model)
End Function
Here is the model I’ve used
Public Class ContactDetails
Public Property Contact As contact
Public Property Meetings As IEnumerable(Of meeting)
Public Property Interviews As IEnumerable(Of interview)
Public Property Opportunites As IEnumerable(Of opportunite)
End Class
Sorry if my english sucks, I’m not a native english speaker.
edit :
I’m not allowed to answer, so I’ll edit with the “solution” I found
I finally fixed it like that :
<div class="display-field">
@If Model.Contact.FK_contact_client Then
@Model.Contact.client.nomCompteClient
End If
</div>
FK_contact_client is the FK that refers to the client the contact is working for.
Weren’t there any better possibility?
Your question doesn’t really has anything to do with ASP.NET MVC. It’s a basic .NET question about object references. You have designed an object hierarchy with properties and sub-properties. In order to be able to access
Model.Contact.client.nomCompteClientyou need to initialize first theContactproperty, and then theclientproperty.Here you seem to be fetching the contact from the database:
Make sure that in the returned object, the
clientproperty is initialized otherwise you cannot use it.For example here:
this displays nothing because the
Contactproperty is not null but theciviliteproperty even if it is null or empty you no longer try to call any method or property on it.