如何检索具有未知输入字段计数的表单中的所有值

huangapple go评论85阅读模式
英文:

How to retrieve all values from a from that can have unknown input field count

问题

以下是翻译好的内容:

我有一个简单的表单,允许用户编辑存在于另一个表单内的下拉列表。在这个表单中,用户可以查看当前的下拉列表值,编辑它们,删除它们或创建更多的值。

这会在一个模态框中打开这个表单:

在这里,您可以编辑现有的值,删除它们或添加新的:

因此,它最终可能包含任意数量的值!

这个CSHTML代码如下:

@using (Html.BeginForm("EditDropDown", "Incidents", FormMethod.Post, new { onsubmit = "validateCustomTolerances()", id = "modal-form" }))
{
  @foreach (var opt in Model.IncRptOptions)
  {
    @if (opt.Type == "Action")
      {
        <div class="IncRpt-opt-modalDisp">
          <input type="text" id="" name="" value="@opt.TypeValue">
          <a class="edit-dropdown delete-existing"><i class="bi bi-trash3-fill"></i></a>
        </div>
      }
   }
   <div id="additional-options-here"></div>
   <a class="btn btn-sm btn-secondary" id="add-option">Add Option</a>
   <br>
   @*------ Hidden form content (required by controller action) ------*@
   <input id="optionType" type="hidden" name="optionType" value="Action" />

   @*------ Form buttons ------*@
   <div class="modal-form-btns">
     <button type="submit" class="btn btn-sm btn-primary modal-save-btn">Save</button>
     <button type="button" class="btn btn-sm btn-secondary">Cancel</button>
   </div>
}

这是JS代码:

<script>
    // 当用户点击“bin”按钮时删除旁边的现有选项。
    document.querySelectorAll('.delete-existing').forEach(item => {
        item.addEventListener('click', event => {
            let existingParent = item.parentElement;
            existingParent.remove();
        });
    });

    // “添加选项”按钮的事件监听器
    let addOption = document.querySelector('#add-option');

    // 当按钮被点击时,创建额外选项的表单输入元素
    addOption.addEventListener('click', function () {
        let parent = document.querySelector('#additional-options-here');
        let html = `
                <input type="text" id="test" name="" value="">
                <a class="edit-dropdown delete-added"><i class="bi bi-trash3-fill"></i></a>
                `;
        let template = document.createElement('div');
        template.setAttribute('class', 'IncRpt-opt-modalDisp');
        template.innerHTML = html;
        let finalHTML = template;
        finalHTML.querySelector('.delete-added').addEventListener('click', deleteAddedElement);
        parent.appendChild(finalHTML);
    });

    // 当用户点击“bin”图标时删除已添加的选项元素
    function deleteAddedElement() {
        let parent = this.parentElement;
        parent.remove();
    }
</script>

由于这个结果,我不知道会返回多少个值。

使用Flask时,我使用了 request.form.getList("Input-name-value")。在ASP.NET中,有没有类似的方法?

英文:

I have a simple form, that allows the user to edit a drop down list that exists within another form. In this the user can view the current drop down list values, edit them, delete them or create more values.

如何检索具有未知输入字段计数的表单中的所有值

This opens this form in a modal:

如何检索具有未知输入字段计数的表单中的所有值

Here you can edit existing values, delete them or add new:

如何检索具有未知输入字段计数的表单中的所有值

So it can end up having any number of values!

The CSHTML for this:

@using (Html.BeginForm(&quot;EditDropDown&quot;, &quot;Incidents&quot;, FormMethod.Post, new { onsubmit = &quot;validateCustomTolerances()&quot;, id = &quot;modal-form&quot; }))
{
  @foreach (var opt in Model.IncRptOptions)
  {
    @if (opt.Type == &quot;Action&quot;)
      {
        &lt;div class=&quot;IncRpt-opt-modalDisp&quot;&gt;
          &lt;input type=&quot;text&quot; id=&quot;&quot; name=&quot;&quot; value=&quot;@opt.TypeValue&quot;&gt;
          &lt;a class=&quot;edit-dropdown delete-existing&quot;&gt;&lt;i class=&quot;bi bi-trash3-fill&quot;&gt;&lt;/i&gt;&lt;/a&gt;
        &lt;/div&gt;
      }
   }
   &lt;div id=&quot;additional-options-here&quot;&gt;&lt;/div&gt;
   &lt;a class=&quot;btn btn-sm btn-secondary&quot; id=&quot;add-option&quot;&gt;Add Option&lt;/a&gt;
   &lt;br&gt;
   @*------ Hidden form content (required by controller action) ------*@
   &lt;input id=&quot;optionType&quot; type=&quot;hidden&quot; name=&quot;optionType&quot; value=&quot;Action&quot; /&gt;

   @*------ Form buttons ------*@
   &lt;div class=&quot;modal-form-btns&quot;&gt;
     &lt;button type=&quot;submit&quot; class=&quot;btn btn-sm btn-primary modal-save-btn&quot;&gt;Save&lt;/button&gt;
     &lt;button type=&quot;button&quot; class=&quot;btn btn-sm btn-secondary&quot;&gt;Cancel&lt;/button&gt;
   &lt;/div&gt;
}

The JS:

&lt;script&gt;
    // Deletes the existing option next to the &#39;bin&#39; button user clicks it. 
    document.querySelectorAll(&#39;.delete-existing&#39;).forEach(item =&gt; {
        item.addEventListener(&#39;click&#39;, event =&gt; {
            let existingParent = item.parentElement;
            existingParent.remove();
        });
    });

    // Event listeners for the &#39;add option&#39; button
    let addOption = document.querySelector(&#39;#add-option&#39;);

    // Creates the form input element for an additional option when button clicked
    addOption.addEventListener(&#39;click&#39;, function () {
        let parent = document.querySelector(&#39;#additional-options-here&#39;);
        let html = `
                &lt;input type=&quot;text&quot; id=&quot;test&quot; name=&quot;&quot; value=&quot;&quot;&gt;
                &lt;a class=&quot;edit-dropdown delete-added&quot;&gt;&lt;i class=&quot;bi bi-trash3-fill&quot;&gt;&lt;/i&gt;&lt;/a&gt;
                `;
        let template = document.createElement(&#39;div&#39;);
        template.setAttribute(&#39;class&#39;, &#39;IncRpt-opt-modalDisp&#39;)
        template.innerHTML = html;
        let finalHTML = template;
        finalHTML.querySelector(&#39;.delete-added&#39;).addEventListener(&#39;click&#39;, deleteAddedElement);
        parent.appendChild(finalHTML);
    });

    // Deletes the added option elements when user clicks on the &#39;bin&#39; icons
    function deleteAddedElement() {
        let parent = this.parentElement;
        parent.remove();
    }
&lt;/script&gt;

As a result, I do not know how many values will be returned.

Using Flask I used request.form.getList(&quot;Input-name-value&quot;). What is the ASP.NET equivalent way of doing this?

答案1

得分: 0

没有人回答这个问题,这没关系。但是不理解为什么会有负评!无论如何,我成功解决了这个问题,所以想为后代提供以下代码。

我发现我可以使用 IFormCollection 接口,然后像下面的代码一样使用 TryGetValue 方法。这将把表单中的值赋给 StringValues,可以进行循环处理。

[HttpPost]
public ActionResult EditDropDownList(IFormCollection collection, int ID)
{
    if ((collection.TryGetValue("optionType", out StringValues LogTypes)) && (collection.TryGetValue("optionValue", out StringValues TypeValues)))
    {
        string logTypeText = string.Empty;
        string typeValueText = string.Empty;
        for (int i = 1; i <= TypeValues.Count; i++)
        {
            logTypeText += LogTypes[i - 1] + ",";
            typeValueText += TypeValues[i - 1] + ",";
        }
    }

    return RedirectToAction("RptPage", new RouteValueDictionary(new { Controller = "Home", Action = "Rpt", IncID = ID }));
}

希望对你有所帮助!

英文:

So no one answered this, which is fine. Do not understand the down vote though! Anyway, I managed to fix this and so thought I would provide this below for future generations.

I found that I could use the IFormCollection Interface and then use the the TryGetValue Method as in the below code. This then assigns the values from the form to StringValues that are able to be looped through.

[HttpPost]
public ActionResult EditDropDownList(IFormCollection collection, int ID)
{
   if ((collection.TryGetValue(&quot;optionType&quot;, out StringValues LogTypes)) &amp;&amp;     (collection.TryGetValue(&quot;optionValue&quot;, out StringValues TypeValues)))
      {
         string logTypeText = string.Empty;
         string typeValueText = string.Empty;
         for (int i = 1; i &lt;= TypeValues.Count; i++)
            {
               logTypeText += LogTypes[i - 1] + &quot;,&quot;;
               typeValueText += TypeValues[i - 1] + &quot;,&quot;;
            }
         }

   return RedirectToAction(&quot;RptPage&quot;, new RouteValueDictionary(new { Controller = &quot;Home&quot;, Action = &quot;Rpt&quot;, IncID = ID }));
}

huangapple
  • 本文由 发表于 2023年6月9日 00:09:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76433822.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定