简体   繁体   English

如何将带有对象列表的数据 object 传递给 controller

[英]How to pass data object with list of objects to controller

I am junior (or less than junior) in IT.我在 IT 方面是初级(或低于初级)。 I have a problem with passing data from view to controller... What I want to achieve: When user click:我在将数据从视图传递到 controller 时遇到问题...我想要实现的目标:当用户单击时:

 <button type="submit" class="btn btn-primary">Dodaj kategorię</button>

I want pass whole object "Category" to controller (also with List Subcategory).我想将整个 object“类别”传递给 controller(也带有列表子类别)。 Second button with id="addSubCategory" will add a field to enter the next subcategory, but I want to send everything after clicking the type = submit button. id="addSubCategory" 的第二个按钮将添加一个字段以输入下一个子类别,但我想在单击 type = submit 按钮后发送所有内容。 How can I pass all subcategories name to list and send one post method?如何将所有子类别名称传递给列表并发送一种发布方法?


That is my View:那是我的观点:

 @model AplikacjaFryzjer_v2.Models.Category @{ ViewData["Title"] = "Dodaj nową kategorię"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h1>Dodaj nową kategorię</h1> <form method="post"> <div class="row"> <div class="col-md-6"> <div asp-validation-summary="All" class="text-danger"></div> <div class="form-group"> <label asp-for="Name"></label> <input asp-for="Name" /> <span asp-validation-for="Name" class="text-danger"></span> </div> <button type="submit" class="btn btn-primary">Dodaj kategorię</button> </div> <div class="col-md-6 offset-6"> <div asp-validation-summary="All" class="text-danger"></div> <div class="form-group"> <label asp-for="Subcategories"></label> <input asp-for="Subcategories" /> <span asp-validation-for="Subcategories" class="text-danger"></span> </div> <button class="btn btn-primary" id="addSubCategory" value="table">Dodaj podkategorię</button> </div> </div> </form>

My Action CreateCategory in controller:我在 controller 中的操作 CreateCategory:

        [HttpPost]
    public IActionResult CreateCategory(Category category)
    {
        _categoriesRepository.AddCategory(category);
        return RedirectToAction("ManageCategories");
    }

And my object (model):还有我的 object(型号):

    public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Subcategory> Subcategories {get;set;}
}

For submitting complex models, you need to ensure that the name attribute of these controls bound to the Subcategory class fields are displayed in the form of a collection index .提交复杂模型时,需要确保这些绑定到子类别 class 字段的控件的名称属性以集合索引的形式显示

And trigger the addSubCategory click event in js to add Subcategory control and data.并在js中触发addSubCategory点击事件,添加Subcategory控件和数据。

Since you added model validation, I suggest you use ViewBag.Subcategories to save the Subcategories data that has been added to the current page to prevent data loss after clicking the validation .由于您添加了 model 验证,我建议您使用ViewBag.Subcategories保存已添加到当前页面的 Subcategories 数据,以防止单击验证后数据丢失

And you only need to add an asp-validation-summary in your form.您只需要在表单中添加一个 asp-validation-summary Since these fields belong to a model and are in a form, their error information will be counted in the asp-validation-summary div.由于这些字段属于一个 model 并且在一个表单中,因此它们的错误信息将计入 asp-validation-summary div。

Here is a complete example:这是一个完整的例子:

   public class Category
    {
        public int Id { get; set; }
        [Required] 
        public string Name { get; set; }
        public List<Subcategory> Subcategories { get; set; }
    }

    public class Subcategory
    { 
        [Required]
        [DisplayName("Subcategory.Name")]
        public string Name { get; set; }
    }

Controller: Controller:

public IActionResult CreateCategory()
        {
            ViewBag.Subcategories = new List<Subcategory>() { };
            return View();
        }

        [HttpPost]
        public IActionResult CreateCategory(Category category)
        {
            if (!ModelState.IsValid)
            {
                // store Subcategories data which has been added
                ViewBag.Subcategories = category.Subcategories == null ? new List<Subcategory>() { } : category.Subcategories;
                return View("CreateCategory");

            }
             _categoriesRepository.AddCategory(category);
            return RedirectToAction("ManageCategories");
        }

View:看法:

@model AplikacjaFryzjer_v2.Models.Category
@{
    ViewData["Title"] = "Dodaj nową kategorię";
    Layout = "~/Views/Shared/_Layout.cshtml";

    var SubcategoriesData = (IList<AplikacjaFryzjer_v2.Models.Subcategory>)ViewBag.Subcategories;

}

<h1>Dodaj nową kategorię</h1>
<form method="post">
    <div class="row">
        <div class="col-md-6">
            <div class="form-group">
                <label asp-for="Name"></label>
                <input asp-for="Name" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <button type="submit" class="btn btn-primary">Dodaj kategorię</button>
        </div>
        <div class="col-md-6 offset-6">
            @for (int i = 0; i < SubcategoriesData.Count(); i++)
            {
                <div class="form-group">
                    <label>Name@(i)</label>
                    <input asp-for="Subcategories[i].Name" value="@SubcategoriesData[i].Name" />
                    <span asp-validation-for="Subcategories[i].Name" class="text-danger"></span>
                </div>
            }
            <button class="btn btn-primary" onclick="RemoveSubcategory(this)" id="removeSubcategory">remove</button>
            <button class="btn btn-primary" id="addSubCategory" value="table">Dodaj podkategorię</button>
        </div> 
        <div asp-validation-summary="All" class="text-danger"></div>
    </div>

</form>
@section Scripts
{
    <script>

     var i = @SubcategoriesData.Count()-1;
    $(document).ready(function () {
        if (@SubcategoriesData.Count() <= 0) {
            $("#removeSubcategory").hide();
        }

        $("#addSubCategory").click(function (e) {
            e.preventDefault();
            i++;
            var name = '<label>Name' + i + '</label><input name = "Subcategories[' + i + '].Name" type="text"/>'; 
            $("#removeSubcategory").before('<div class="form-group">' + name  + '</div>');
            $("#removeSubcategory").show();
        });


    });
    function RemoveSubcategory(btn) {
        event.preventDefault();
        $(btn).prev("div").remove();
        i--;
        if (i == @SubcategoriesData.Count() -1) {
            $("#removeSubcategory").hide();
        }
    }
    </script>
}

Here is test result:这是测试结果:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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