Snow
Snow

Reputation: 87

ASP.NET Core trouble in model binding

I'm new in ASp.NET Core. All data saved in database correctly, i tried show model data in View. Person model data gotten correctly, but second model Address didn't show in View. I suspect I made a mistake in the controller.

First model:

public class Person
    {
        public int PersonID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Address HomeAddress { get; set; }
    }

Second model:

public class Address
    {
        public int ID { get; set; }
        public string Line { get; set; }
        public string City { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }

        public int PersonId { get; set; }
        public Person Person { get; set; }
    }

Controller code:

public IActionResult Index()
        {

            return View(_repository.Persons);
        }
        [HttpGet]
        public ViewResult Create()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Create(PersonCreateViewModel p)
        {
            var obj = new Person
            {
                FirstName = p.FirstName,
                LastName = p.LastName,
                BirthDate = p.BirthDate,
                HomeAddress = p.HomeAddress,
                Role = p.Role,
                IsApproved = p.IsApproved
            };
            _repository.Add(obj);
            return View();
        }

View:

@model IEnumerable<Person>
@{
    ViewData["Title"] = "Home Page";
}
<div class="text-center">
    @foreach(var p in Model)
    {
        <p>Name - @p.FirstName</p>
        <p>Last Name - @p.LastName</p>
        <p>Role - @p.Role</p>
        <p>Line - @p.HomeAddress?.Line</p>
        <p>City - @p.HomeAddress?.City</p>
    }
    <hr />
</div>

Upvotes: 0

Views: 104

Answers (1)

yousif
yousif

Reputation: 682

As the user Mustapha Larhrouch said in his comment, one way to fix this is to use the include method on your property to load related data, so _repository.Persons.Include(p => p.Adress)

There are several ways Entity Framework Core loads related data from Database like Eager loading, Explicit loading and Lazy loading, the method above is called Eager loading

I suggest you take a look at Loading Related Data from MS docs. Or the lazy loading section in Querying in Entity Framework Core

Upvotes: 2

Related Questions