簡體   English   中英

在ASP.NET Core MVC App中添加動態表單字段

[英]Add dynamic form fields in ASP.NET Core MVC App

在我的應用中,我想創建可以具有動態屬性列表的模型:

提供者類別

using System;
using System.Collections.Generic;

namespace DynamicForms.Models
{
    public class Provider
    {
        public String Name { get; set; }
        public List<Attribute> Attributes { get; set; }

        public Provider()
        {
            Attributes = new List<Attribute>();
        }
    }
}

我的控制器有兩種方法。 一種是向當前模型添加更多屬性,另一種是保存提供者模型。 添加更多屬性的方法如下所示:

    [HttpPost]
    // Add attribute to current provider model
    public IActionResult Index(Provider provider)
    {
        provider.Attributes.Add(new Models.Attribute());
        return View(provider);
    }

我的看法如下所示:

@model Provider
@using (Html.BeginForm())
{
    <div>
        @Html.TextBoxFor(m => m.Name)
        <input type="submit" value="Add attribute" formmethod="post"/>
    </div>
    <div>
        @foreach ( var attribute in Model.Attributes)
        {
        <div>
            @Html.TextBoxFor(a => attribute.Name)
            @Html.TextBoxFor(a => attribute.Value)
        </div>
        }
    </div>
    <div>
        <input type="submit" value="Save form" formaction="Provider/Save" formmethod="post"/>
    </div>
}

當我按下“添加屬性”按鈕時,將添加屬性並出現一行輸入字段。 但是,當我再按一次按鈕時,什么也沒有發生。 沒有添加其他行。 模型屬性數量仍然為1。我一直在網上尋找解決方案,但找不到能解決我問題的任何方法。 如何使表單字段動態添加到模型並在vieW中顯示?

嘗試用索引而不是foreach遍歷列表,例如

@for (var i = 0; i < Model.Attributes.Count; i++)
{
  <div>
    @Html.TextBoxFor(a => Model.Attributes[i].Name)
    @Html.TextBoxFor(a => Model.Attributes[i].Value)
  </div>
}

您希望對名稱進行格式設置,例如Attributes [0] .Name等。

您為Post編寫了一個方法,但為get編寫了一個方法。

獲取方法

   public IActionResult Index()
    {
        Provider provider = new Provider();
        provider.Attributes.Add(new Models.Attribute());
        return View(provider);
    }

后方法

   [HttpPost]
    // Add attribute to current provider model
    public IActionResult Index(Provider provider)
    {
        provider.Attributes.Add(new Models.Attribute());
        return View(provider);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM