V
V
Viktor Familyevich2020-05-27 16:47:25
ASP.NET
Viktor Familyevich, 2020-05-27 16:47:25

Why ParentCategory=null?

The site has services that are divided into categories Category
model

public class Category : EntityBase
    {
[Required]
        public Guid Id { get; set; }
        [Display(Name = "Услуги")]
        public IEnumerable<Service> Services { get; set; }
    }

Service Model
public class Service : EntityBase
    {
[Required]
        public Guid Id { get; set; }
        [Required]
        [Display(Name = "Название")]
        public override string H1 { get; set; }
        [Display(Name = "Категория")]
        public Category ParentCategory { get; set; }
    }

When opening a service, the categories that are displayed on the form are passed to ViewBag.Categories
public IActionResult Edit(Guid id)
        {
            var entity = id == default ? new Domain.Entities.Service() : dataManager.Services.GetServiceById(id);
            ViewBag.Categories = new SelectList(dataManager.Categories.GetCategories(), "Id", "H1", entity.ParentCategory);
            return View(entity);
        }

In the Edit view, a form is made in which this model is selected
<form asp-area="Admin" asp-controller="Services" asp-action="Edit" method="post" enctype="multipart/form-data">
   <div>
        <label asp-for="ParentCategory"></label>
        <select asp-for="ParentCategory" asp-items="ViewBag.Categories"></select>
        <span asp-validation-for="ParentCategory"></span>
    </div>



When submitting this form, ParentCategory returns null for some reason.
Tell me how to fix?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Planet_93, 2020-05-27
@Wintego

Or write virtual for the given data model field.

public class Service : EntityBase
    {
[Required]
        public Guid Id { get; set; }
        [Required]
        [Display(Name = "Название")]
        public override string H1 { get; set; }
        [Display(Name = "Категория")]
        public virtual Category ParentCategory { get; set; }
    }

Or use Include().
dataManager.Services.GetAll().Include(x => x.ParentCategory).FirstOrDefault(x => x.Id ==id);

EntityFramefork by default does not pull complex objects, i.e. records from related tables.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question