0

I have an Object, say Employee with the following:

 Employee() { int id; string name; } 

In my view,

I currently do

<input type="text" name="employeeName" id="employeeName" readonly="true" value="@Model.Employee.name"/> 

However, in certain cases the Employee value will be null and this will give me an error, null reference error. Should I do inline checks to return an empty string if it's null or is there a better way?

would the @HTML.TextboxFor() method work better in this case?

6
  • 1
    Why would you manually create a textbox with name="employeeName" which has no relationship to you model and will not be bound on post back (your model does not have a property named employeeName)? Use @Html.TextBoxFor(m => m.name, new { readonly = "readonly" }) Commented May 19, 2015 at 1:08
  • Oh I just made the above up on the fly. But it served as an example. Commented May 19, 2015 at 1:29
  • You using MVC so make use of its features. Always use strongly typed helpers to bind to your model properties :) Commented May 19, 2015 at 1:31
  • 1
    One additional point: you can also declaratively say how to display nulls: stackoverflow.com/a/17273132/49251. Commented May 19, 2015 at 1:45
  • 1
    @DWright, DisplayFormat.NullDisplayText is only respected by @Html.DisplayFor() (not by TextForFor() or EditorFor()) Commented May 19, 2015 at 2:17

1 Answer 1

5

Using Html.TextBoxFor would handle this, yes:

@Html.TextBoxFor(i => i.Employee.Name) 

This will not cause a null issue. You can also use your approach with null checks, so your assumption is correct:

<input type="text" name="employeeName" id="employeeName" readonly="true" value="@(Model.Employee != null ? Model.Employee.name : "")"/> 

This is because you are using the objects directly, whereas TextBoxFor evaluates the expression tree and handles nulls appropriately.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.