如何将表单输入绑定到字典值

zaz*_*aza 0 c# asp.net-core razor-pages

我正在创建一个ASP.NET核心剃须刀页面Web应用程序,其中一个页面需要能够修改Dictionary<string, string>属性。

我尝试修改的对象如下:

public class Element
{
    [Key]
    public string ID {get;set;}
    public Dictionary<string, string> Values = new Dictionary<string, string>(); 
}
Run Code Online (Sandbox Code Playgroud)

我可以使用以下代码来支付页面上的值:

<form method="POST">
    <ul>
        <li hidden="true">ID: <input asp-for="FocusedItem.ID"/></li>
        @for (int i = 0; i < Model.FocusedItem.Values.Count(); i++)
        {
            <li>@Model.FocusedItem.Values.ElementAt(i).Key: <input asp-for="@Model.FocusedItem.Values.ElementAt(i).Value"/></li>
        }
    </ul>
    <br />
    <input type="submit" value="Submit" />
</form>
Run Code Online (Sandbox Code Playgroud)

Pagemodel包含以下方法来处理发布事件:

public void OnPost(Element FocusedItem)
{
}
Run Code Online (Sandbox Code Playgroud)

“ ID”属性已正确填充,但是“ Values”属性的计数为0(表单上的输入值未绑定到词典)。如何解决这个问题?

另外还有一个问题-如何将新元素添加到字典中?

编辑:代码--cshtml:https: //raw.githubusercontent.com/thezaza101/RDMUI/master/Pages/Data/ElementManager.cshtml -cs:https : //raw.githubusercontent.com/thezaza101/RDMUI/master/Pages /Data/ElementManager.cshtml.cs

Chr*_*att 5

@MarkG接近,但实际语法为:Values[N].KeyValues[N].ValueN您的索引在哪里。但是,由于您正在使用标签助手来生成字段,所以真正的问题是您使用ElementAt。模型表达式不能包含任意方法,因为无法绑定到类似ElementAt结果POST处理中的东西。相反,您必须使用索引语法,即[i]。但是,在某些地方使用字典会失败,因为它无法通过项目位置(仅是键)进行索引。

老实说,我倾向于避免发布字典,因为它是非结构化数据。99.99%的时间可能最好将其分解为具有属性而不是键字典的类。如果您坚持使用字典,则可以尝试将实际键值作为索引器传递:

@foreach (var key in Model.Values.Keys)
{
    <input asp-for="Values[key]" />
}
Run Code Online (Sandbox Code Playgroud)

我没有亲自尝试过,但是我认为它应该可以工作。简而言之,我知道可行的唯一方法是手动生成输入名称:

<input name="Values[@i].Key" value="@Model.Values.ElementAt(i).Key" />
<input name="Values[@i].Value" value="@Model.Values.ElementAt(i).Value" />
Run Code Online (Sandbox Code Playgroud)