Answer the question
In order to leave comments, you need to log in
How to get related entities in a POST request?
Hello colleagues. The problem is this. There is a controller method that accepts a POST request to edit the model (Normal blog post), in this model I want to get the associated post entities, let's say comments or tags, but the ToList () methods do not return these entities, although there is a connection. Here is the controller method code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Post post)
{
//Валидность модели
if (ModelState.IsValid)
{
//Ждем в асинхроном режиме результат сохранения
db.SaveChanges();
foreach (var item in post.Comments.ToList())
{
Debug.WriteLine(item.Text);
}
//Редирект на страницу поста
return RedirectToAction("Details", new { id = post.Id });
}
return View(post);
}
@model BlogEmpty.Models.Post
@{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.EditorForModel(Model);
<input type="submit" value="Редактировать" class="btn btn-default" />
}
<div>
@Html.ActionLink("К списку", "Index")
</div>
Answer the question
In order to leave comments, you need to log in
Off topic answer. And changes in basis occur in general? It is not clear in your code what db is. It is clear to me that this is the EntityFramework context, but where and how it is initialized is not clear to me, and based on this, it is not clear to me what you are doing by calling db.saveChanges()
. Where there is a change of objects in a context - I do not see.
Making the controller code dependent on the EntityFramework is BAD(!!!!!!) It's simple, of course, but it's bad. This is a cruel dependency that requires constant editing of source codes - output such operations in the DataAccessLayer.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question