Jed
Jed

Reputation: 15

How to fix my model returning a list with a null parameter?

I am trying to create a simple blog where a user can register an account, and create blog posts. I am using the built-in single user account system, but have extended this to be "ApplicationUser" which contains two fields: List, and List. I have yet to implement comments, and I am first working on adding and displaying posts.

I am able to create posts and users successfully, but when trying to display all the posts in the system, the Poster field is null. The schema for the Post class is: {ID, Title, Body, Poster, TimePosted, Comments}. I put a breakpoint in my code and Poster (the ApplicationUser) shows as null.

What I am trying to achieve is to display: [Blog Title] by [Username] at [Date]

I loop through each item in the Model, and it prints everything correctly, except for the line:

@Html.DisplayFor(modelItem => item.Poster.UserName)

which displays an empty string.

I have used the SQL Server Object Explorer to view the data in the database, and Users and Posts are stored correctly. The ID of the user who creates the post displays the correct ID. It shows that the foreign key is set up correctly.

Post Class:

namespace BlogApp.Models
{
    public class Post
    {

        [Required, Key]
        public int ID { get; set; }

        [Required]
        public string Title { get; set; }

        [Required]
        public string Body { get; set; }

        [Required]
        public virtual ApplicationUser Poster { get; set; }

        [Required]
        public DateTime TimePosted { get; set; }

        [Required]
        public List<Comment> Comments { get; set; }

    }
}

Index.cshtml view for PostsController:

@foreach (var item in Model.Reverse())
{
    <div class="post">
        <a asp-action="Details" asp-route-id="@item.ID">
            <h3>"@Html.DisplayFor(modelItem => item.Title)", by 
@Html.DisplayFor(modelItem => item.Poster.UserName) on 
@Html.DisplayFor(modelItem => item.TimePosted)</h3>
        </a>
        <p>@Html.DisplayFor(modelItem => item.Body)</p>
    </div>
}

In this example, everything displays correctly except item.Poster.UserName. The entire Poster object is null, and not a single attribute of the Poster/ApplicationUser is accessible.

Index() method for PostsController:

public async Task<IActionResult> Index()
{
    return View(await _context.Post.ToListAsync());
}

I have tried separating this logic by first assigning the result of ToListAsync() to "var list", and then returning View(list). When using a breakpoint, I discovered that the Poster object within the list variable is null.

The problem is the Poster object is not being passed properly to the view. However, I am unable to find the solution.

Upvotes: 0

Views: 377

Answers (1)

Hooman Bahreini
Hooman Bahreini

Reputation: 15559

Have you tried Eager Loading using Include?

await _context.Post.Include(p => p.Poster).ToListAsync();

Upvotes: 2

Related Questions