How to view my content from my database to my home view in .Net core MVC

Assadullah Sanusi 20 Reputation points
2025-01-18T15:28:13.7133333+00:00

Hi guys

SO I was learning to use .NET Core MVC through the tutorial, and I decided to take it up a notch. While the tutorial has been helpful, it did not really have what I was looking for, and surprisingly, neither do all the AI bots. So what's the issue? Well, I want to render all my movies that I have in my movie list on my home page from the database instead of generically adding them from a folder. The reason I am doing it like this is that if a movie is deleted from the database, it logically should not be available for watching. The main issue I am having is that instead of the thumbnails showing, it runs the else logic. It's as if it is not factoring in the entire condition.

Here's my code:

@model MvcMovie.Models.MovieGenreViewModel`
@{
    ViewData["Title"] = "Home Page";
}
<div class="text-center">
    <h1 class="display-4-bold">Relive your <span class="text-warning">childhood</span> with all the <span style="color:blueviolet">cool movies you missed</span></h1>
    <p>Will you <a asp-controller="Movies" asp-action="Index" style="color: blueviolet; font-weight: bold;">Checkout our library</a>.</p>
</div>
<div class="container-fluid">
    <div class="row">
        @if (Model?.Movies != null && Model.Movies.Any())
        {
            foreach (var movie in Model.Movies)
            {
                <div class="col-md-4 mb-4">
                    <div class="card shadow-sm">
                        @if (!string.IsNullOrEmpty(movie.Image))
                        {
                            <img src="@movie.Image" class="card-img-top" alt="@movie.Title" style="height: 300px; object-fit: cover;" />
                        }
                        else
                        {
                            <img src="https://via.placeholder.com/300x300" class="card-img-top" alt="No image available" />
                        }
                        <div class="card-body">
                            <h5 class="card-title text-truncate">@movie.Title</h5>
                            <p class="card-text text-truncate">
                                Genre: @movie.Genre <br />
                                Rating: @movie.Rating <br />
                                Release Date: @movie.ReleaseDate.ToShortDateString()
                            </p>
                            <a asp-controller="Movies" asp-action="Details" asp-route-id="@movie.Id" class="btn btn-primary btn-sm">View Details</a>
                        </div>
                    </div>
                </div>
            }
        }
        else
        {
            <div class="col">
                <p class="text-center text-muted">No movies available in the database.</p>
            </div>
        }
    </div>
</div>

Please incase the error is not from my home/index, let me know where to look at.

Thanks.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,757 questions
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,389 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,244 questions
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,926 Reputation points Microsoft Vendor
    2025-01-21T02:21:31.2166667+00:00

    Hi @Assadullah Sanusi

    so here's the index of my movie page, as you can see there are movies displayed. These movies are fetched from the database, the way it is shown here is the same way I want it to display on my home page.

    To display movies list in Home page, you can try the following steps:

    1.In the HomeController, change the Index action as below: register the MvcMovieContext and query database to get the movie list, then return it to view page:

               public class HomeController : Controller
               {
                   private readonly ILogger<HomeController> _logger;
                   private readonly MvcMovieContext _context;
                   public HomeController(ILogger<HomeController> logger, MvcMovieContext context)
                   {
                       _logger = logger;
                       _context = context;
                   }
                   public async Task<IActionResult> Index(string movieGenre, string searchString)
                   {
                       if (_context.Movies == null)
                       {
                           return Problem("Entity set 'MvcMovieContext.Movie' is null.");
                       }
                       // Use LINQ to get the list of genres
                       IQueryable<string> genreQuery = from m in _context.Movies
                                                       orderby m.Genre
                                                       select m.Genre;
                       // Query movies
                       var movies = from m in _context.Movies
                                    select m;
                       if (!string.IsNullOrEmpty(searchString))
                       {
                           movies = movies.Where(s => s.Title != null && s.Title.ToUpper().Contains(searchString.ToUpper()));
                       }
                       if (!string.IsNullOrEmpty(movieGenre))
                       {
                           movies = movies.Where(x => x.Genre == movieGenre);
                       }
                       var movieGenreVM = new MovieGenreViewModel
                       {
                           Genres = new SelectList(await genreQuery.Distinct().ToListAsync()),
                           Movies = await movies.ToListAsync() // Ensures Movies is a List<Movie>
                       };
                       return View(movieGenreVM);
                   }
    
    

    2.In the Home Index view page, refer to the following code (you can copy the code from your movie index page) to display the movie:

            @model MvcMovie.Models.MovieGenreViewModel
    
            @{
                ViewData["Title"] = "Index";
            }
    
            <h1>Index</h1>
    
            <p>
                <a asp-action="Create">Create New</a>
            </p>
            <form asp-controller="Movies" asp-action="Index" method="get">
                <p>
    
                    <select asp-for="MovieGenre" asp-items="Model.Genres">
                        <option value="">All</option>
                    </select>
    
                    <label>Title: <input type="text" asp-for="SearchString" /></label>
                    <input type="submit" value="Filter" />
                </p>
            </form>
    
            <table class="table">
                <thead>
                    <tr>
                        <th>
                            @Html.DisplayNameFor(model => model.Movies![0].Title)
                        </th>
                        <th>
                            Thumbnail
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => model.Movies![0].ReleaseDate)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => model.Movies![0].Genre)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => model.Movies![0].Price)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => model.Movies![0].Rating)
                        </th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var item in Model.Movies!)
                    {
                        <tr>
                            <td>
                                @Html.DisplayFor(modelItem => item.Title)
                            </td>
                            <td>
                                <img src='@item.Image' style="width:50px;hight:50px" alt="Thumbnails" />
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.ReleaseDate)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.Genre)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.Price)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.Rating)
                            </td>
                            <td>
                                <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                                <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                                <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
    
    

    Then, the movie should display in the home page.

    Note:

    From your database screenshot, it seems that you are stored the image using base64 string, so, in my sample, the Movie.cs class like this:

            public class Movie
            {
                public int Id { get; set; }
                [StringLength(60, MinimumLength = 3)]
                [Required]
                public string? Title { get; set; }
                [Required]
                public string? Image { get; set; }
                [Display(Name = "Release Date")]
                [DataType(DataType.Date)]
                public DateTime ReleaseDate { get; set; }
                [Range(1, 100)]
                [DataType(DataType.Currency)]
                [Column(TypeName = "decimal(18, 2)")]
                public decimal Price { get; set; }
                [RegularExpression(@"^[A-Z]+[a-zA-Z\s]*$")]
                [Required]
                [StringLength(30)]
                public string? Genre { get; set; }
                [RegularExpression(@"^[A-Z]+[a-zA-Z0-9""'\s-]*$")]
                [StringLength(5)]
                [Required]
                public string? Rating { get; set; }
            }
    

    Finally, in the Home page, the result as below:

    enter image description here


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. SurferOnWww 3,811 Reputation points
    2025-01-19T00:15:13.2133333+00:00

    I guess that your post is based on the following Microsoft Movie tutorial:

    Get started with ASP.NET Core MVC

    If so, your requirement below;

    I want to render all my movies that I have in my movie list on my home page from the database instead of generically adding them from a folder. The reason I am doing it like this is that if a movie is deleted from the database, it logically should not be available for watching.

    will be realized if you proceed with the steps in tutorial up to "Part 5, work with a database in an ASP.NET Core MVC app."

    However, your issue stated below does not make sense to me.

    The main issue I am having is that instead of the thumbnails showing, it runs the else logic. It's as if it is not factoring in the entire condition.

    Can you tell me some more details about what you want to do?

    0 comments No comments

  2. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.

    1 deleted comment

    Comments have been turned off. Learn more

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.