简体   繁体   中英

asp.net core how can i post category and subcategory from table row

Here is my Category.cs,

public class Category
{
    public int Id { get; set; }
    [Required, StringLength(100),Display(Name="Category Name")]
    public string Name { get; set; }
    [Display(Name="Category Description")]
    public string Description { get; set; }
    public bool IsActive { get; set; }
    public IList<Style> Style { get; set; }
    public IList<SubCategory> SubCategories { get; set; }
}
public class SubCategory
{
    public int Id { get; set; }
    public string Value { get; set; }
}
public class IndexModel : PageModel
{
    [Microsoft.AspNetCore.Mvc.BindProperty]
    public Category ViewModel { get; set; }
    public void OnGet()
    {
        // You can fill your ViewModel property here.
    }
    public void OnPost()
    {
        // You can read your posted ViewModel property here.
    }
}

And DbContext.cs

public DbSet<Category> Categories { get; set; }
public DbSet<SubCategory> SubCategory { get; set; }

And AddCategory.cshtml

@model UretimPerformans.Entity.Admin.IndexModel
@{
ViewData["Title"] = Localizer["addca"];
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}

@section Scripts{
    <link href="~/dist/plugins/bootstrap-switch/css/bootstrap3/bootstrap-switch.min.css" rel="stylesheet" />
    <script src="~/js/jquery-3.5.1.js"></script>
    <style>
        td, tr {
            text-align: center;
            vertical-align: middle;
        }
    </style>
}

    @section Scripts2{
    <script src="~/dist/plugins/bootstrap-switch/js/bootstrap-switch.js"></script>

    <script>
        $("#btnSearch").click(function () {
            var t = null;
            t = $("#tab_logic tbody tr").get().map(function (tr) {
                return $(tr).find("input").get().map(function (input) {
                    return input.value
                })
            })

            $("#regTitle").html(t);
        });
    </script>

    <script>
        $(document).ready(function () {
            var i = 1;
            $("#add_row").click(function () {
                $('#addr' + i).html("<td>" + (i + 1) + "</td><td><input name='name" + i + "' required type='text' placeholder='SubCategory-" + i + "' class='form-control input-md'  /> </td><td><input  name='mail" + i + "' type='checkbox' placeholder='IsActive'  class='form-control'></td>");

                $('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
                i++;
            });
            $("#delete_row").click(function () {
                if (i > 1) {
                    $("#addr" + (i - 1)).html('');
                    i--;
                }
            });
        });


        $(function () {

            $("input[data-bootstrap-switch]").each(function () {
                $(this).bootstrapSwitch('state', $(this).prop('checked'));
            });

        })
    </script>
}
<section class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1>@Localizer["addca"]</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a asp-action="Index" asp-controller="Home">@Localizer["anasayfa"]</a></li>
                    <li class="breadcrumb-item"><a asp-action="Index" asp-controller="Catalog">@Localizer["cat"]</a></li>
                    <li class="breadcrumb-item"><a asp-action="Categories" asp-controller="Catalog">@Localizer["ca"]</a></li>
                    <li class="breadcrumb-item active">@Localizer["addca"]</li>
                </ol>
            </div>
        </div>
    </div>
</section>
<section class="content">
    <div class="card">
        <div class="card-body">
            <form asp-action="AddCategories" asp-controller="Catalog" method="post">
                <div class="form-group row">
                    <span class="col-md-3">@Localizer["name"]</span>
                    <div class="col-md-9">
                        <input type="text" class="form-control" asp-for="ViewModel.Name" required />
                    </div>
                </div>
                <div class="form-group row">
                    <span class="col-md-3">@Localizer["desc"]</span>
                    <div class="col-md-9">
                        <textarea type="text" id="regTitle" class="form-control" asp-for="ViewModel.Description" required></textarea>
                    </div>
                </div>
                <div class="form-group row">
                    <span class="col-md-3">@Localizer["aktif"]</span>
                    <div class="col-md-9">
                        <input type="checkbox" asp-for="ViewModel.IsActive" checked data-bootstrap-switch data-off-color="danger" data-on-color="success">
                    </div>
                </div>
                <fieldset class="module">
                    <h4>@Localizer["alt"]</h4>

                    <button id="btnSearch">Click</button>
                    <a id="add_row" class="btn btn-default pull-left">Add Row</a>
                    <a id='delete_row' class="pull-right btn btn-default">Delete Row</a>
                    <hr />
                    <div class="row clearfix">
                        <div class="col-md-12 column">
                            <table class="table table-bordered table-hover" id="tab_logic">
                                <thead>
                                    <tr>
                                        <th class="text-center">
                                            #
                                        </th>
                                        <th class="text-center">
                                            SubCategoryName
                                        </th>
                                        <th class="text-center">
                                            IsActive
                                        </th>
                                    </tr>
                                </thead>
                                <tbody>                                    
                                        <tr id='addr0'>
                                            <td>1</td>                                            
                                            <td>
                                                <input asp-for="ViewModel.SubCategories[1].Value" />
                                                @Model.ViewModel.SubCategories[1].Value
                                            </td>
                                        </tr>
                                    
                                    <tr id='addr0'>
                                        <td>
                                            1
                                        </td>
                                        <td>
                                            <input type="text" name='name0' placeholder='Name' class="form-control" />
                                        </td>
                                        <td>
                                            <input type="checkbox" name='mail0' placeholder='Mail' class="form-control" />
                                        </td>
                                    </tr>
                                    <tr id='addr1'></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </fieldset>
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">@Localizer["kaydet"]</button>
                </div>
            </form>
        </div>
    </div>
</section>

And CategoryController,

        [HttpGet]
        public IActionResult AddCategories()
        {
            return View();
        }
        [HttpPost]
        public IActionResult AddCategories(Category entity)
        {
            if (ModelState.IsValid)
            {
                categoryRepository.AddCategory(entity);
                TempData["success"] = "Başarıyla kaydedildi.";
                return RedirectToAction("Categories");
            }
            else
            {
                return View(entity);
            }
        }

My codes are as above. What I want to do is add subcategories from the table at the bottom of the category when adding a category. but I could not set up the model. and I could not write the post method and reading method in indexmodel. Please can you help me?

Thank you Kind Regards

I don't understand the meaning of name0 and name1..., neither Category nor SubCategory have this attribute. In addition, if you add SubCategoryName by adding a row in the table, this SubCategory class does not have the attribute 'IsActive'. If you only want to add SubCategories through the rows of the table, you can follow this example. Here I simulate some data.

public class IndexModel : PageModel
{
    [Microsoft.AspNetCore.Mvc.BindProperty]
    public Category ViewModel { get; set; }
    public void OnGet()
    {
        ViewModel = new Category
        {
            Id = 1,
            Description = "desc",
            IsActive = false,
             Name="name",
              SubCategories=new List<SubCategory>
              {
                  new SubCategory
                  {
                       Id=10,Value="val"
                  },
                  new SubCategory
                  {
                       Id=20,Value="val2"
                  },
                  new SubCategory
                  {
                       Id=30,Value="val3"
                  },
              }
        };
        // You can fill your ViewModel property here.
    }
}

I find discorrect asp-controller here.

Because the name in the form starts with 'ViewModel', the mapped model should be modified like this.

[HttpPost]
    public IActionResult AddCategories(Category ViewModel)
    {
        //...
        return Json(ViewModel);
    }

Then, the result is as follows. 在此处输入图片说明

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