Reputation: 2491
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?
Upvotes: 0
Views: 5403
Reputation: 50728
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.
Upvotes: 5