ASP.net-core Razor 模型绑定列表与 select

问题描述 投票:0回答:1

我正在尝试使用 razor 页面进入 asp.net core。我对无法修改的数据库使用数据库优先方法。在我正在处理的页面中,我想显示一些用户可以选择分数的概念。每个概念都有不同的可能分数列表,用户可以从中选择。

获取正确,表单正确显示带有项目的选择以及从数据库加载的选择。

我的问题是,当我尝试发布它所包含的表单时,模型状态不会验证分数并且概念列表为空。

我不明白为什么“概念”列表在该状态下为空。其他属性运行良好。谁能解释一下吗?

提前感谢您的回答

我的看法

@foreach (var EvalComp_Notion in Model.Notions)
{
    <tr>
        <td>
            <select class="form-control" asp-for="@EvalComp_Notion.Note">
                @foreach (var choix in EvalComp_Notion.NotePossibles)
                {
                    <option class="form-control" value="@choix.Key">@choix.Value</option>
                }
            </select>
        </td>
    </tr>
}

还有我的页面模型

[BindProperty]
public List<VM_Notion> Notions { get; set; } = new List<VM_Notion>();

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

    foreach(var ECN in EC.EvaluationCompetenceNotions)
    {
        Notions.Add(new VM_Notion()
        {
            Nom = ECN.Notion.Nom,
            Note = ECN.Note,
            Commentaire = ECN.Commentaire,
            NotePossibles = ECN.Notion.NotionEvalChoixes.Select(nec => new { Rg = nec.Rang, ch = nec.EvaluationChoix.Descr }).OrderBy(x => x.Rg).ToDictionary(ec => ec.Rg, ec => ec.ch)
        });
    }
// the notions list is correctly populated at this stage

    return Page();
}

public async Task<IActionResult> OnPostAsync()
{
    // the List<Notion> notions is empty here, so there is nothing to validates
    if (!ModelState.IsValid)
    {
        return Page();
    }

    // in here I should get the model and modify it according to the form's result

    try
    {
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException)
    {
        
    }

    return Page();
}

public class VM_Notion
{
    public int Note { get; set; }
    [ValidateNever]
    public Dictionary<int, string?> NotePossibles { get; set; } = new Dictionary<int, string?>();
}
asp.net-core razor razor-pages
1个回答
0
投票

foreach 循环中,模型绑定器无法通过名称正确绑定列表实体的属性,因为每个实体具有相同的名称。改为使用 for 循环进行绑定。索引将有助于绑定正确的属性。

<form method="post">
    <table>
        @for (int i = 0; i < Model.Notions.Count; i++)
        {
            <tr>
                <td>
                    <select asp-for="@Model.Notions[i].Note" class="form-control">
                        @foreach (var choix in Model.Notions[i].NotePossibles)
                        {
                            <option class="form-control" value="@choix.Key">@choix.Value</option>
                        }
                    </select>
                </td>
            </tr>
        }
    </table>
    <button type="submit" class="btn btn-primary">Submit2</button>
</form>

© www.soinside.com 2019 - 2024. All rights reserved.