A
A
Anton Tarara2016-04-14 11:01:23
ASP.NET
Anton Tarara, 2016-04-14 11:01:23

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);
        }

Presentation code:
@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>

e5231d44a8eb4d1288c51981c5f6354a.png
In general, the question is, why is this happening and what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Kovalsky, 2016-04-14
@atarara

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 question

Ask a Question

731 491 924 answers to any question