【发布时间】:2019-04-01 18:23:29
【问题描述】:
我需要创建一个表单来收集来自用户的多个键值对数据。我正在使用字典来建模这些数据。在我的表单中,用户插入一个键和值,如果需要添加不止一对,则按下 (+) 图标以显示新字段。如果用户决定删除键值对,则需要单击删除图标来删除键值对。我开始使用 jQuery 和 JavaScript 对表单的行为进行编码,因为后端是用 C# 制作的,但很快它就开始变得更加复杂。我曾尝试使用 Razor 页面和 asp 标签助手,但它们对创建我想要的事件序列没有帮助。我想知道如何在 ASP.Net Core 2.2 中最恰当地解决这种情况
<div id="otherProperty">
<i id="deleteProperty" class="material-icons">delete</i>
<input id="otherPropertyKey" name="propertyKey" type="text" placeholder="Property name"/>
<input id="otherPropertyValue" name="propertyValue" type="text" placeholder="Property value"/>
<i id="addProperty" class="material-icons"></i>
</div>
<div>
<input id="submitBtn" type="submit" value="Submit"/>
</div>
OtherProperties 的模型是:
public class OtherProperties:IOtherProperties
{
private readonly Dictionary<string, string> _otherProperties;
public OtherProperties()
{
_otherProperties = new Dictionary<string, string>();
}
public Dictionary<string, string> GetOtherProperties()
{
return _otherProperties;
}
public void AddProperty(string key, string value)
{
if (!_otherProperties.ContainsKey(key))
{
_otherProperties.Add(key,value);
}
}
public void RemoveProperty(string key)
{
if (_otherProperties.ContainsKey(key))
{
_otherProperties.Remove(key);
}
}
}
接口在哪里
public interface IOtherProperties
{
Dictionary<string, string> GetOtherProperties();
void AddProperty(string key, string value);
void RemoveProperty(string key);
}
【问题讨论】:
-
pssst,这不是 JS 或 jQuery 问题。这是一个 .net/mvc 问题
-
在 razor 页面中使用集合中的索引,并制作一个具有简单 KeyValue 对象的公共列表的模型
-
不幸的是,这太宽泛了。一天结束时,ASP.Net、Core 或任何版本不会更改 HTTP 请求/响应。也就是说,您可以在客户端使用任何风格的 JS/Library 和
POST构建您的有效负载到控制器进行处理 - 同样,以任何风格:映射/绑定到model或通过 raw 请求参数。 -
请提供您的控制器代码。
OtherProperties在哪里使用? -
@Alexander 我已经回答了这个问题。稍后我也会提供 Blazor 解决方案。
标签: asp.net asp.net-mvc asp.net-core razor