我正在创建一个ASP.NET核心剃须刀页面Web应用程序,其中一个页面需要能够修改A
属性。
我要修改的对象如下:
Dictionary<string, string>
我可以使用以下代码来支付页面上的值:
public class Element
{
[Key]
public string ID {get;set;}
public Dictionary<string, string> Values = new Dictionary<string, string>();
}
pagemodel包含以下方法来处理发布事件:
<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>
“ 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
答案 0 :(得分:2)
@MarkG接近,但实际语法为:Values[N].Key
和Values[N].Value
,其中N
是您的索引。但是,由于您正在使用标记助手来生成字段,所以真正的问题是您使用ElementAt
。模型表达式不能包含任意方法,因为在结果POST处理中无法绑定到ElementAt
之类的东西。相反,您必须使用索引语法,即[i]
。但是,在某些地方,字典无法使用,因为字典无法通过项目位置(仅是键)进行索引。
老实说,我倾向于避免发布字典,因为它是非结构化数据。 99.99%的时间可能最好将其分解为具有属性而不是键字典的类。如果您坚持使用字典,则可以尝试将实际键值作为索引器传递:
@foreach (var key in Model.Values.Keys)
{
<input asp-for="Values[key]" />
}
我还没有亲自尝试过,但我认为应该可以。简而言之,我知道的唯一方法是手动生成输入名称:
<input name="Values[@i].Key" value="@Model.Values.ElementAt(i).Key" />
<input name="Values[@i].Value" value="@Model.Values.ElementAt(i).Value" />