Home > Software design >  My view is empty while displaying in ASP.NET MVC
My view is empty while displaying in ASP.NET MVC

Time:11-14

I work with a database and I want to display it on the view. After debugging it seems that my model is empty. I created a similar project before where it worked fine but I don't find the problem in my code.

How can I fix it?

My class:

namespace Persons.Data
{
    public class Person
    {
        public int Id { get; get; }

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

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

DbContext:

namespace Persons.Data
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext([NotNullAttribute] DbContextOptions options) : base(options)
        {

        }

        public DbSet<Person> Persons { get; set; }
    }
}

Controller:

namespace Persons.Controllers
{
    public class PeopleController : Controller
    {
        private readonly ApplicationDbContext _context;

        public PeopleController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: People
        public async Task<IActionResult> Index()
        {
            return View(await _context.Persons.ToListAsync());
        }
    }
}

My view:

@model IEnumerable<Persons.Data.Person>

@{
    ViewData["Title"] = "Index";
}

@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.LastName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.FirstName)
            </td>
        </tr>
}

CodePudding user response:

try not to put async and sync code in one line

 public async Task<IActionResult> Index()
        {
            var model = await _context.Persons.ToListAsync();

            // stop debugger here and check a model data

            return View(model);
        }

CodePudding user response:

Are you sure that your _context.Persons.ToListAsync() has data?

Because if it is empty the view will display nothing, you can try to add a simple label in your view to make sure this works fine.

  • Related