【问题标题】:Issues with binding multiple objects on a razor page在剃须刀页面上绑定多个对象的问题
【发布时间】:2019-11-26 06:09:30
【问题描述】:

我正在尝试构建一个剃须刀页面,允许用户在单个页面上编辑多个不同的对象 - 特定测试将在实验室中在单个测试运行下运行。我一直在兜圈子,现在已经到了这样的地步: 1. 回帖页面好像是清除了页面上的父(testRun)对象上的一些数据,但是重新加载的时候数据保持不变 2.对子对象(testRowFatContent)的更改保留在页面上,但不保存在数据库中,并在页面重新加载时消失。

我的目标是让用户能够编辑页面上的任何对象,单击保存,并将值返回到屏幕并保存在数据库中。

我已经尝试强制修改实体框架状态,但这似乎并不是最好的解决方案(因为我需要在 cshtml 页面上创建隐藏的输入字段来捕获完整的对象),我不确定如何设置要标记为已修改的对象列表。我怀疑我缺少原始数据绑定的一些基本内容,但在搜索 Microsoft 页面和 stackoverflow 后无法弄清楚。在阅读了一些表明这可能是问题的文章后,我确实删除了一个@foreach 循环,并将其替换为带有 cshtml 内索引的@for 循环。

namespace KookaburraLab.Pages.TestRun
{
    public class RunTests : PageModel
    {
        private readonly KookaburraLab.Models.KookaburraLabContext _context;

        public RunTests(KookaburraLab.Models.KookaburraLabContext context)
        {
            _context = context;
        }
        [BindProperty]
        public KookaburraLab.Models.TestRun TestRun { get; set; }
        [BindProperty]
        public List<TestRowFatContent> testRowFatContents { get; set; }
        [BindProperty]
        public List<TestRowSaltExtract> testRowSaltExtracts { get; set; }
        [BindProperty]
        public List<TestRowWaterAbsorption> testRowWaterAbsorptions { get; set; }
        [BindProperty]
        public List<TestRowTensileStrength> testRowTensileStrength { get; set; }

        public async Task<IActionResult> OnGetAsync(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            TestRun = await _context.TestRun.SingleOrDefaultAsync(m => m.TestRunID == id);

            if (TestRun == null)
            {
                return NotFound();
            }

            testRowFatContents = await _context.TestRowFatContent.Where(t => t.TestRunID == id).ToListAsync();
            testRowWaterAbsorptions = await _context.TestRowWaterAbsorption.Where(t => t.TestRunID == id).ToListAsync();
            testRowSaltExtracts = await _context.TestRowSaltExtract.Where(t => t.TestRunID == id).ToListAsync();
            testRowTensileStrength = await _context.TestRowTensileStrength.Where(t => t.TestRunID == id).ToListAsync();
            return Page();
        }

        public async Task<IActionResult> OnPostSaveChangesAsync()
        {

            _context.SaveChanges(); 
            //ModelState.Clear();
            testRowFatContents = await _context.TestRowFatContent.Where(t => t.TestRunID == TestRun.TestRunID).ToListAsync();
            testRowWaterAbsorptions = await _context.TestRowWaterAbsorption.Where(t => t.TestRunID == TestRun.TestRunID).ToListAsync();
            testRowSaltExtracts = await _context.TestRowSaltExtract.Where(t => t.TestRunID == TestRun.TestRunID).ToListAsync();
            testRowTensileStrength = await _context.TestRowTensileStrength.Where(t => t.TestRunID == TestRun.TestRunID).ToListAsync();

            return Page();
        }

        public async Task<IActionResult> OnPostCloseTestAsync()
        {
            return Page();
        }
    }
}
 <form method="post" enctype="multipart/form-data">

        <button type="submit" class="btn btn-success btn-sm" asp-page-handler="SaveChanges">Save Changes</button>
        <button type="submit" class="btn btn-danger btn-sm" asp-page-handler="CloseTest">Abandon Test Run</button>
        <input type="hidden" asp-for="TestRun.TestRunID" />
        <input type="hidden" asp-for="TestRun.TestItemCreatedUser" />
        @*<div>
            <partial name="_TestRowFatContent"/>
        </div>*@

        <div>
            @if (Model.testRowFatContents.Count > 0)
    {
            <h4>Fat Content Test</h4>
            <table class="table">
                <thead>
                    <tr>
                        <th>
                            @Html.DisplayNameFor(model => model.testRowFatContents[0].TestRowStatus)
                        </th>

                        <th>
                            @Html.DisplayNameFor(model => model.testRowFatContents[0].TestRowSampleDescription)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => model.testRowFatContents[0].w1EmptyFlask)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => model.testRowFatContents[0].w2ThimbleWeight)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => model.testRowFatContents[0].w3ThimbleLeatherWeight)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => model.testRowFatContents[0].w4LeatherWeight)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => model.testRowFatContents[0].w5FlaskExtractWeight)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => model.testRowFatContents[0].w6ExtractWeight)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => model.testRowFatContents[0].FatContent)
                        </th>
                        @*<th>
                            @Html.DisplayNameFor(model => model.testRowFatContents[0].TestItemID)
                        </th>*@
                        <th>
                            @Html.DisplayNameFor(model => model.testRowFatContents[0].TestRowSampleID)
                        </th>

                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    @for (int i=0; i < Model.testRowFatContents.Count(); i++)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(modelItem => Model.testRowFatContents[i].TestRowStatus)
                        </td>
                        <td>
                            <input asp-for="@Model.testRowFatContents[i].TestRowSampleDescription" class="form-control" />
                            <input type="hidden" asp-for="@Model.testRowFatContents[i].TestRowID" />

                        </td>
                        <td>
                            <input asp-for="@Model.testRowFatContents[i].w1EmptyFlask" class="form-control" />
                        </td>
                        <td>
                            <input asp-for="@Model.testRowFatContents[i].w2ThimbleWeight" class="form-control" />
                        </td>
                        <td>
                            <input asp-for="@Model.testRowFatContents[i].w3ThimbleLeatherWeight" class="form-control" />
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => @Model.testRowFatContents[i].w4LeatherWeight)
                        </td>
                        <td>
                            <input asp-for="@Model.testRowFatContents[i].w5FlaskExtractWeight" class="form-control" />
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => @Model.testRowFatContents[i].w6ExtractWeight)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => @Model.testRowFatContents[i].FatContent)
                        </td>
                        @*<td>
                            @Html.DisplayFor(modelItem => item.TestItemID)
                        </td>*@
                        <td>
                            @Html.DisplayFor(modelItem => @Model.testRowFatContents[i].TestRowSampleID)
                        </td>

                        @*<td>
                            <a asp-page="./Edit" asp-route-id="@item.TestRowID">Edit</a> |
                            <a asp-page="./Details" asp-route-id="@item.TestRowID">Details</a> |
                            <a asp-page="./Delete" asp-route-id="@item.TestRowID">Delete</a>
                        </td>*@
                    </tr>
}

任何帮助将不胜感激 - 如果我错过了一些明显的事情,请提前道歉。

在调试时,我已经确认 OnPost 处理程序正在被调用,并且模型状态正确地反映了新的(更改的)值 - 它似乎丢失了 dbcontext,我认为它应该在 GET 和 POST 调用中维护在 .NET 核心中。我真的很想避免为每个特定类型手动指定对 dbcontext 的更新,因为我可能会有大量使用此页面的项目。我还尝试使用似乎不起作用的 AttachRange(testFatContents),无论我是否将其包含在 GET 或 POST 处理程序中(或两者都包含!)

我有一个类似结构的页面,可以将新项目添加到运行良好的 dbcontext,

【问题讨论】:

  • 根据您发布的代码,您的 OnPostSavechanges 方法不太可能被调用。方法名称不遵循约定,并且您的表单没有指定命名的处理程序方法,您应该从这里开始:learnrazorpages.com/razor-pages/handler-methods 以了解处理程序方法的命名约定,然后转到learnrazorpages.com/razor-pages/model-binding,重点关注关于复杂集合的部分。跨度>
  • 嗨迈克,感谢您的回复!到目前为止,learnrazorpages.com 网站一直很有帮助。 OnPostSaveChangesAsync 通过按钮上定义的处理程序被调用 - 我已经在调试中确认了这一点。我看到模型状态正确地反映了更改的项目(即表单上公开的输入字段),但是 dbcontext 似乎失去了对对象的跟踪。当我在 get 上运行查询后查看 dbcontext 时,一切看起来都不错,但是在帖子上,dbcontext 没有我的类型的本地变量。将更新原帖。
  • 我会接受这可能是我错了,因为我刚开始玩 .net core,但我认为这种说法不正确。 “我认为这意味着要在 .NET 核心中的 GET 和 POST 调用中进行维护。”网络是无状态的,任何实体都将失去其更改跟踪。您可以查看进行注入的库
  • 谢谢 Tyddlywink - 我怀疑你是对的,只是想知道是否有一种聪明的方式来处理它 - 我只是担心如果我必须编写特定的处理来将对象附加到上下文中我将编写大量重复代码来捕获所有值(根据我对附加到上下文的理解,然后手动将 entityState 设置为 modified 将用新值替换所有旧值)。
  • 啊。我完全忽略了按钮的属性。出现您的问题是因为您没有将更改应用于上下文。提供更全面的答案。

标签: c# entity-framework-core razor-pages


【解决方案1】:

您正在调用_context.SaveChanges(),这是在数据库上保存更改的正确方法,但是您没有告诉数据库您要更改什么。

您希望使用模型绑定来收集您的用户发送到服务器的表单数据。

public async Task<IActionResult> OnPostSaveChangesAsync(List<TestRowFatContent> testRowFatContents, List<TestRowSaltExtract> testRowSaltExtracts, List<TestRowWaterAbsorption> testRowWaterAbsorptions, List<TestRowTensileStrength> testRowTensileStrength)
{
    //Check if your list objects are filled with the user input, the name attribute of the input fields need to match the variable names above

    //tell the context what you want to update 
    _context.UpdateRange(testRowFatContents);
    _context.UpdateRange(testRowSaltExtracts);
    _context.UpdateRange(testRowWaterAbsorptions);
    _context.UpdateRange(testRowTensileStrength);
    _context.SaveChanges(); 

    return Page();
}

在实体框架中更新有时有点棘手,但重要的部分是您在 SaveChanges() 方法中拥有数据,然后告诉您的数据库如何处理它。

如果您有未包含在表单中的字段,它们将被覆盖,因为 EF 只是准确地保存了您从模型绑定中获得的对象。为避免未使用的字段被覆盖,您可以包含隐藏的输入字段或使用 EF 的 IsModified 属性。您必须在不想更改的属性上设置它。

例子:

_context.Entry(testRowFatContents).Property("FatContent").IsModified = false;

【讨论】:

  • 非常感谢 Elias 和 Mike - 事后看来是如此明显!为了有效地使用它,我是否需要填充 cshtml 上对象中的每个元素? (即包含 testRowFatContents 的每个字段作为隐藏输入) - 我刚刚运行修改后的代码并保存了对象,但删除了一些在此特定页面中未使用的字段。
  • 我编辑了我的答案,让我知道这是否适合你。顺便说一句,您绝对应该查看有关 ASP.NET 的 Mike Brinds 博客。我大约一年前开始使用 Razor Pages,他的博客很快成为我获取框架信息和指南的第一来源
【解决方案2】:

提交表单时,表单数据会正确绑定到 PageModel 属性,但这些更改不会应用于上下文。您在断开连接的情况下工作 - 页面内的状态 - 包括上下文 - 不会跨请求维护。每次执行页面时都会重建它。当页面作为 POST 请求的结果执行时,状态由 modelbinder 构建。因此,您必须将重构(更改)的实体附加到上下文,并告诉上下文它们处于(修改)的状态。然后上下文将知道要应用哪些更改。

EF Core 提供了一个 UpdateRange 方法,旨在让上下文知道集合已被修改,例如

_context.UpdateRange(testRowFatContents);
await _context.SaveChangesAsync();

在此处查看有关在断开连接的情况下工作的更多信息:https://www.learnentityframeworkcore.com/dbcontext/modifying-data#disconnected-scenario

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 2021-11-23
    • 2020-05-30
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多