Search code examples
c#asp.net-mvc-viewmodel

How can I check if a ViewModel's property is null in a View?


In a C# MVC 5 View, how can I check if a ViewModel's property is null?

Here is my @model code:

@model DataService.ViewModels.MVC.UserViewModel

The UserViewModel has a property as follows:

public User userParent
{
    get
    {
        return _userParent;
    }
    set
    {
        _userParent = value;
    }
}

Here is my View code:

<dd>
    @if (model.userParent != null)
    {
        @Html.DisplayFor(modelItem => model.userParent.name)
    }
    else
    {

    }
</dd>

I am getting the following compiler error:

Compiler Error Message: CS0103: The name 'model' does not exist in the current context


Solution

  • Replace model with Model. Notice the case of the first letter.