john john - 3 months ago 10
C# Question

How to display message if User doesn't have created list items

Im using the default web application mvc 5 template project with asp.net identity.
I have a Movie.cs model, and associated each User to have a Movies list, so when you register you can go and add movies in the list with CRUD, and im showing them on the home page.

enter image description here

my viewmodel:

@model MovieApp.ViewModels.UserMovieViewModel
@using MovieApp.Models;

<div class="row" style="margin-top:60px">
@using (ApplicationDbContext db = new ApplicationDbContext())
{
if (db.Users.Any())
{
foreach (var _user in Model.ApplicationUser)
{
<div class="col-md-4">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">@_user.UserName</h3>
</div>
<div class="panel-body">
<ul>
@foreach (var _movie in _user.Movies.Where(x => x.ApplicationUserID == _user.Id))
{
<li>@_movie.MovieName</li>
}
</ul>
</div>
</div>
</div>
}
}
else
{
<h2 class="alert alert-danger text-center">No movie lists</h2>
}
}

</div>


If i have a user that hasn't added any movies in the list, then i got null exception error for this line:

@foreach (var _movie in _user.Movies.Where(x => x.ApplicationUserID == _user.Id))


so how to display message (like in the picture below)in the list under each user if the user hasn't created any movies?

enter image description here

Answer

You can easily achieve this by checking whether there is any movie or not inside .panel-body like this:

<div class="panel-body">
    @if(_user.Movies != null && _user.Movies.Any()) {
        <ul>
            @foreach (var _movie in _user.Movies.Where(x => x.ApplicationUserID == _user.Id)) 
            {
                <li>@_movie.MovieName</li>
            }
        </ul>
    } 
    else 
    {
        <p>No movies...</p>
    }
</div>