【问题标题】:How to edit nested collections in MVC5?如何在 MVC5 中编辑嵌套集合?
【发布时间】:2015-10-07 10:13:00
【问题描述】:

我有一个包含“键”和“值”的 EF 模型。值表包含键的 FK。在 EF 模型中,它看起来像这样:

public partial class dict_key
{
    public dict_key()
    {
        this.dict_value = new HashSet<dict_value>();
    }
    public int id { get; set; }
    public string name { get; set; }
    ...
    public virtual ICollection<dict_value> dict_value { get; set; } //dict_value contains a string "value"
}

我的控制器正在传递信息以进行编辑,如下所示:

// GET: Keys/Texts/5
[Authorize]
public async Task<ActionResult> Texts(int? id)
{
    var key = await db.dict_key
        .Include(x => x.dict_value)
        .Where(x => x.id.Equals(id.Value))
        .FirstOrDefaultAsync();
    return View(key);
    // Debugging 'key' shows that dict_value has 3 correct values.
}

这会传递给我的视图,显示 dict_value 是正确的:

@model Dict.Models.dict_key
@using (Html.BeginForm())
{
    <div>Key: @Model.name </div>
    <table class="table">
        <tr>
            <th>Language</th>
            <th>Text</th>
        </tr>
        @for (var i = 0; i < Model.dict_value.Count(); i++)
        {
            <tr>
                <td> @Model.dict_value.ElementAt(i).dict_lang.name_en </td>
                <td> @Html.EditorFor(x => x.dict_value.ElementAt(i).value) </td>
            </tr>
        }
        <div class="form-group">
            <input type="submit" value="Save" />
        </div>
    </table>
}

将我的更改提交回控制器时...

[HttpPost]
public async Task<ActionResult> Texts(dict_key dict_key)
{
    if (ModelState.IsValid)
    {
        //Also tried: db.Entry(dict_key).State = EntityState.Modified;
        db.Entry(dict_key.dict_value).State = EntityState.Modified;
        await db.SaveChangesAsync();
        return RedirectToAction("Texts");
    }
    return View(dict_key);
}

..那么我的“dict_key”与我传递给我的编辑视图的对象完全不同。传递的对象包含 dict_value 的集合,“返回”和编辑的对象返回正确的键对象,但带有一个空的 dict_value 集合。

我尽量避免使用用户定义的模型或视图包来手动完成所有这些工作。对此的最佳实践解决方案是什么?

【问题讨论】:

    标签: entity-framework razor asp.net-mvc-5


    【解决方案1】:

    Collection.ElementAt 不会在 Razor 中生成正确的字段名称。你需要一个List。在这里,您应该直接使用视图模型而不是您的实体,并简单地将您的 dict_value 集合设为 List&lt;dict_value&gt; 那里。

    或者,您可以为dict_value 创建一个编辑器模板,然后在您的视图中执行以下操作:

    @Html.EditorFor(m => m.dict_value)
    

    dict_value 是您的全部收藏。 Razor 将为集合的每个成员呈现编辑器模板的实例并正确索引所有内容。

    【讨论】:

      猜你喜欢
      • 2014-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 2015-04-22
      • 2016-07-28
      相关资源
      最近更新 更多