0
<li>
   <%=Html.UITemplates().FieldLong().TextBox("OrderRequest.AdditionalParties[0].ContactDetails[0].Address.Line1", "Address", Model.OrderRequest.AdditionalParties[0].Address.Line1)%>
</li>

The above line when Address is null throws a null reference exception. I don't know how to handle it as I still want to display view while Address.Line1 should be displayed as empty string.

7
  • What is Html.UITemplates().FieldLong().TextBox()? Its not part of MVC Commented Feb 18, 2016 at 21:30
  • 1
    Model.OrderRequest.AdditionalParties[0].Address == null ? string.Empty : Model.OrderRequest.AdditionalParties[0].Address.Line1 %> try this. Commented Feb 18, 2016 at 21:31
  • You'll need to null-check every part of that object chain. Just the Address property is taking a risk. It's better to work with smaller models to keep things clean. Commented Feb 18, 2016 at 21:33
  • @StephenMuecke yes it's not part of mvc. They are custom html helpers in my project. Commented Feb 18, 2016 at 21:54
  • 1
    The you should show them. If you have written this helper correctly, then all you need is Html.UITemplates().FieldLong().TextBox("OrderRequest.AdditionalParties[0].ContactDetails[0].Address.Line1") which will set the value attribute to value="" if its null, and no exception will be thrown Commented Feb 18, 2016 at 21:57

1 Answer 1

2

You can simply use the conditional operator to check the null values on any object. So in your case it would be:

Model.OrderRequest.AdditionalParties[0].Address == null ? string.Empty : Model.OrderRequest.AdditionalParties[0].Address.Line1 %>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.