【问题标题】:Update list from Razor View using Entity Framework Core使用 Entity Framework Core 从 Razor 视图更新列表
【发布时间】:2020-10-09 05:17:03
【问题描述】:

我在从 Razor View 表更新时遇到了挑战,不确定我的方法是否正确。我没有在 DIV 中显示数据(要编辑),而是在 TABLE 中显示。我可以理解隐藏属性是如何用于更新行的。就我而言,我在“编辑”页面上显示了多行,但无法仅为已更新的行更新数据库。

我的查看页面是这样的

<form method="post">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>        
    <table class="table">
        <thead>
            <tr>
                <th> @Html.DisplayNameFor(model => model.Fields[0].Name) </th>
                <th> @Html.DisplayNameFor(model => model.Fields[0].Value) </th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model.Fields)
            {
                <tr>
                    <td> <input type="hidden" asp-for=@item.ID /> </td>
                    <td> @Html.DisplayFor(modelItem => item.Name) </td>
                    <td contenteditable='true'> @Html.DisplayFor(modelItem => item.Value) </td>
                </tr>
            }
        </tbody>
    </table>
    <div class="form-group">
        <input type="submit" value="Save" class="btn btn-primary" />
    </div>
</form>

后面的代码是这样的。 OnPostAsync 方法中的字段显示为 0。

[BindProperty]
    public IList<FieldInfo> Fields { get; set; }
    public async Task<IActionResult> OnGetAsync(string id)
    {
        Fields = await _context.FieldInfo.Where(m => m.GUID == id).ToListAsync();
        return Page();
    }

    public async Task<IActionResult> OnPostAsync()
    {
        foreach (var p in Fields) // In this approach Fields shows as count=0
        {
            _context.Attach(p.Value).State = EntityState.Modified;
        }

        _context.Attach(Fields).State = EntityState.Modified; // In this approach Exception: The entity type 'List<FieldInfo>' was not found.

        await _context.SaveChangesAsync();            
        return RedirectToPage("./Index");
    }

【问题讨论】:

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


    【解决方案1】:

    如果您想使用列表或集合,您必须使用索引来标识单个元素。 https://www.learnrazorpages.com/razor-pages/model-binding#binding-complex-collections

    在你的情况下,我会使用显式索引:

    @foreach (var item in Model.Fields)
    {
        <tr>
            <td> <input type="hidden" asp-for="Fields[item.ID].ID" />  <input type="hidden" name="Fields.Index" value="Fields[item.ID].ID" /></td>
            <td> @item.Name</td>
            <td><textarea asp-for="Fields[item.ID].Value">@Fields[item.ID].Value">@Fields[item.ID].Value</textarea> </td>
        </tr>
    }
    

    请注意,分配给指定为contenteditabletd 的值不会作为表单的一部分发布。您应该使用合适的表单控件,例如 inputtextarea

    【讨论】:

    • 仍然出现同样的错误。不确定我的方法是否被打破
    【解决方案2】:

    在将类型从IList更改为List后,我得到了它的工作

    [BindProperty]
    public List<FieldInfo> Fields { get; set; }
    

    【讨论】:

      猜你喜欢
      • 2018-04-27
      • 2016-06-30
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 2017-08-01
      • 2018-03-21
      • 1970-01-01
      相关资源
      最近更新 更多