简体   繁体   中英

Use partial view to generate dynamic form data

In my app I want to generate ViewModel's Attribute list using PartialView , but I can add only single one, because after adding another it gets put in the place of previous one. Is there a way to do this using PartialView/ViewComponents or any other thing? View with no attributes: 在此输入图像描述 When adding first attribute: 在此输入图像描述 When adding second one the first one is not visible: 在此输入图像描述

@model ProviderViewModel
<form asp-action="Create">
    <div>
        @Html.LabelFor(m => m.Name)
        @Html.TextBoxFor(m => m.Name)
    </div>
    <div>
        @Html.LabelFor(m => m.Url)
        @Html.TextBoxFor(m => m.Url)
    </div>
    <div>
        @Html.Label("Attributes")
    </div>
    @if (Model.Attributes.Count > 0)
    {
        @for (var i = 0; i < Model.Attributes.Count; i++)
        {
            @await Html.PartialAsync("_ProviderAttribute", Model.Attributes[i])
        }
    }
    <div>
        <input type="submit" value="+" formaction="AddAttribute" formmethod="post" />
    </div>
    <br/>
</form>

AddAttribute method simply adds new object to collection. Added Guid to make sure attributes are not the same.

[HttpPost]
        public IActionResult AddAttribute(ProviderViewModel provider)
        {
            provider.Attributes.Add(new AttributeViewModel
            {
                Guid = Guid.NewGuid().ToString()
            });
            return View(nameof(Provider), provider);
        }

Try using javascript to add the new Attribute , the following is the demo I made ,you could modify according to your needs.

ViewModel

public class ProviderViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Url { get; set; }
    public List<AttributeViewModel> Attributes { get; set; }
}

public class AttributeViewModel
{
    public string Guid { get; set; }
    public string Name { get; set; }

}

The main view , Edit: use a hidden input to record the index value of the new Attribute item and the calculation of the index value is implemented in js

@model WebAppDemo.Models.ViewModels.ProviderViewModel

<form asp-action="Create" method="post">
<div>
    @Html.LabelFor(m => m.Name)
    @Html.TextBoxFor(m => m.Name)
</div>
<div>
    @Html.LabelFor(m => m.Url)
    @Html.TextBoxFor(m => m.Url)
</div>
<div>
    @Html.Label("Attributes")
</div>
<div class="attribute">
   <input hidden id="index" value="0"/>
   // render partial view
</div>

<div>
    <input type="button" id="btnAdd" value="+" />
</div>
<br />
</form>

@section Scripts
{
<script type="text/javascript">
    $("#btnAdd").click(function () {
       var num = document.getElementById("index").value;
        $.ajax({
            type: "get",
            url: "/Home/AddAttribute?index=" + num,
            success: function (result) {
                $(".attribute").append(result);
                num++;
                document.getElementById("index").value = num;
            }
        });
    });
</script>
}

AddAttribute method , Edit: use ViewBag to save index

public IActionResult AddAttribute(string index)
    {
        ViewBag.Index = index;
        ProviderViewModel provider = new ProviderViewModel {
            Attributes=new List<AttributeViewModel>()
        };
        provider.Attributes.Add(new AttributeViewModel
        {
            Guid = Guid.NewGuid().ToString()
        });
        return PartialView("_ProviderAttribute", provider);
    }

The _ProviderAttribute Partial View , Edit :for bind Attributes list to the ProviderViewModel from view to controller , define the name attribute of input as follows:

@model WebAppDemo.Models.ViewModels.ProviderViewModel
@{
  ViewData["Title"] = "_ProviderAttribute";
 }
<div class="atrritem">
    <input name="Attributes[@ViewBag.Index].Guid" asp-for="Attributes[0].Guid" class="form-control" />
    <input name="Attributes[@ViewBag.Index].Name" asp-for="Attributes[0].Name" class="form-control" />
    <br />
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM