【问题标题】:Adding multiple set of key-value pair of data in ASP.Net Core with Razor syntax使用 Razor 语法在 ASP.Net Core 中添加多组键值对数据
【发布时间】: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">&#xe147;</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


【解决方案1】:

我终于通过使用 JavaScript 解决了这个问题。如果没有 Blazor,您将无法使用纯 ASP.Net Razor 来实现此目的。我写的 JavaScript 代码如下:

 <div id="otherProperties">
                <div id="otherProperty-0">
                    <i id="deleteProperty-0" class="material-icons" onclick="RemoveProperty(id)">delete</i>
                    <input id="otherPropertyKey-0" name="propertyKey-0" type="text" placeholder="Property name"/>
                    <input id="otherPropertyValue-0" name="propertyValue-0" type="text" placeholder="Property value"/>
                    <i id="addProperty" class="material-icons" onclick="AddProperty()">&#xe147;</i>
                </div>

那么 JavaScript 代码会是这样的

var idCounter = 1;
var keyValuePairArray = ['0']; 


function AddProperty() {
    if(document.getElementById('deleteProperty-'.concat(idCounter-1)) !== null) {
        document.getElementById('deleteProperty-'.concat(idCounter - 1)).style.visibility = 'visible';
    }
    var newProperty = GenerateOtherProperty(idCounter);
    document.getElementById('otherProperties').insertAdjacentHTML('beforeend',newProperty);
    keyValuePairArray.push(idCounter.toString());
    idCounter = idCounter +1 ;
}

function RemoveProperty(id) {
    //from id extract the number
    var propId = id.toString().split('-')[1];
    document.getElementById('otherProperty-'.concat(propId)).remove();
    var index = keyValuePairArray.indexOf(propId.toString(),0);
    if(index > -1){
        keyValuePairArray.splice(index,1);
    }
}

function KeyValuePair(key,value) {
    this.key = key;
    this.value = value;   
}


function GetKeyValueInputBoxes() {
    var otherProps = [];
   for (i =0; i < keyValuePairArray.length; i++){
       var key = GetElement('otherPropertyKey-'.concat(keyValuePairArray[i])).value;
       var value = GetElement('otherPropertyValue-'.concat(keyValuePairArray[i])).value;
       var kvp = new KeyValuePair(key,value);
       otherProps.push(kvp);
   }  
   return otherProps;
}


/**
 * @return {string}
 */
function GenerateOtherProperty (counter) {
     var rawOtherProperty = ' <div id="otherProperty">\n' +
         '                <i id="deleteProperty" class="material-icons" onclick="RemoveProperty(id)">delete</i>\n' +
         '                <input id="otherPropertyKey" name="propertyKey" type="text" placeholder="Property name"/>\n' +
         '                <input id="otherPropertyValue" name="propertyValue" type="text" placeholder="Property value"/>\n' +
         '                 <i id="addProperty" class="material-icons" onclick="AddProperty()">&#xe147;</i>\n' +
         '            </div>';
     var freshProp = new DOMParser().parseFromString(rawOtherProperty,"text/html");
     freshProp.getElementById("otherProperty").id = 'otherProperty-'.concat(counter);
    freshProp.getElementById("deleteProperty").id = 'deleteProperty-'.concat(counter);
    freshProp.getElementById("otherPropertyKey").id = 'otherPropertyKey-'.concat(counter);
    freshProp.getElementById("otherPropertyValue").id = 'otherPropertyValue-'.concat(counter);

     return freshProp.body.innerHTML;   
}

因此,通过使用 JS,我们可以控制 UI 的行为并收集字段中的值。我们会将数据转换为 JSON 对象,并将其作为请求的原始主体 POST 到后面的 Web API 控制器。

        [HttpPost]
        [Route("api/event")]
        public IActionResult ProcessForm([FromBody] JObject jsonRawBody)
        {
            var jsonData = JsonConvert.DeserializeObject<Event>(jsonRawBody.ToString());
           // process jsonData

        }    

事件模型在哪里:

  public class Event
    {
        [JsonProperty("otherKVP")]
        public IList<KeyValuePair<string,string>> OtherProperties { get; set; }

}

【讨论】:

    猜你喜欢
    • 2014-07-05
    • 1970-01-01
    • 2019-09-03
    • 2020-10-02
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多