简体   繁体   中英

creating category and subcategory dependent list box using asp.net core 2.2

I am trying a create a page where I have a form to create the product. here I trying to creating category and subcategory dependent list box.but not understand how I will do that. Here is my code:

public class Category
    {

        public int Id { get; set; }

        [Required]
        [Display(Name = "Category Name")]
        public string CategoryName { get; set; }
    }

//my SubCategory model

 public class SubCategory
    {
        public int Id { get; set; }

        [Required]
        [Display(Name = "SubCategory Name")]
        public string SubCategoryName { get; set; }
    }




//my product model

 public class Product
    {
        public int Id { get; set; }
        [Required]
        public String Name { get; set; }
        [Required]
        [Display(Name = "Category Type")]

        public int CategoryTypeId { get; set; }

        [ForeignKey("CategoryTypeId")]
        public Category Category { get; set; }

        [Required]
        [Display(Name = "SubCategory Type")]

        public int SubCategoryTypeId { get; set; }

        [ForeignKey("SubCategoryTypeId")]
        public SubCategory SubCategory { get; set; }
    }

Product Controller


        [HttpGet]
        public IActionResult Create()
        {
            ViewData["CategoryId"] = new SelectList(_db.Category.ToList(), "Id", "CategoryName");           
            ViewData["SubCategoryId"] = new SelectList(_db.SubCategory.ToList(), "Id", "SubCategoryName");
            return View();
        }


        [HttpPost]
        public async Task<IActionResult> Create(Product product)
        {
            if (ModelState.IsValid)
            {
                
                _db.Product.Add(product);
                await _db.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(product);
        }




Create.cshtml


@model Amazon.Models.Product



@{
    ViewData["Title"] = "Create";
}

<br />



<h2 class="text-info">Add New Product</h2>

<form asp-action="Create" method="post" enctype="multipart/form-data">
    <div class="p-4 rounded border">
        <div asp-validation-summary="ModelOnly" class="text-danger">

        </div>

        <h3>@ViewBag.message</h3>

        <div class="form-group row">
            <div class="col-2">
                <label asp-for="Name"></label>
            </div>
            <div class="col-5">
                <input asp-for="Name" class="form-control" />
            </div>
            <span asp-validation-for="Name" class="text-danger"></span>
        </div>
        <div class="form-group row">
            <div class="col-2">
                <label asp-for="CategoryTypeId"></label>
            </div>
            <div class="col-5">
                <select asp-for="CategoryTypeId" asp-items="ViewBag.CategoryId" class="form-control"></select>
                @*<input asp-for="ProductTypeId" class="form-control" />*@
            </div>
            <span asp-validation-for="CategoryTypeId" class="text-danger"></span>
        </div>
        <div class="form-group row">
            <div class="col-2">
                <label asp-for="SubCategoryTypeId"></label>
            </div>
            <div class="col-5">
                <select asp-for="SubCategoryTypeId" asp-items="ViewBag.SubCategoryId" class="form-control"></select>
                @*<input asp-for="SpecialTagId" class="form-control" />*@
            </div>
            <span asp-validation-for="SubCategoryTypeId" class="text-danger"></span>
        </div>


        <div class="form-group">
            <input type="submit" class="btn btn-primary" value="Save" />
            <a asp-action="Index" class="btn btn-success">Back To List</a>
        </div>
    </div>
</form>

@section Scripts{

    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");

    }
}



above code, I did successfully data-bind of my product controller and view.but I trying to creating category and subcategory dependent list box.but not understand how I will do that. here my expectation output:

在此处输入图像描述

I am an absolute beginner. please help anyone.

I trying to creating category and subcategory dependent list box.

To implement cascading dropdown for Category and Subcategory , as I mentioned in comment, you can populate SubCategory dropdown based on the previous selection of Category in Category dropdown change event, like below.

You can try to modify your model class and implement one-to-many relationship between Category and Subcategory entities, so that you can store data like below in database and retrieve all sub-categories based on the provided CategoryId.

在此处输入图像描述

Populate only Category dropdown when page loads

<div class="form-group">
    <div class="col-2">
        <label asp-for="CategoryTypeId" class="control-label"></label>
    </div>
    <div class="col-5">
        <select asp-for="CategoryTypeId" asp-items="ViewBag.CategoryId" class="form-control">
            <option value="">Select Category</option>
        </select>
    </div>
                
</div>
<div class="form-group">
    <div class="col-2">
        <label asp-for="SubCategoryTypeId" class="control-label"></label>
    </div>
    <div class="col-5">
        <select asp-for="SubCategoryTypeId"></select>
    </div>
</div>

Dynamically populate SubCategory dropdown in Category dropdown change event

$(function () {
    $("select#CategoryTypeId").change(function () {
        var cid = $(this).val();
        
        $("select#SubCategoryTypeId").empty();

        $.getJSON(`/Home/GetSubCategory?cid=${cid}`, function (data) {
            //console.log(data);
            $.each(data, function (i, item) {
                $("select#SubCategoryTypeId").append(`<option value="${item.id}">${item.name}</option>`);
            });
        });
    })
});

Action method GetSubCategory

public IActionResult GetSubCategory(int cid)
{
    var SubCategory_List=_db.SubCategory.Where(s => s.CategoryId == cid).Select(c => new { Id = c.Id, Name = c.SubCategoryName }).ToList();
    return Json(SubCategory_List);
}

Test Result

在此处输入图像描述

Update:

Model classes

public class Category
{
    public int Id { get; set; }

    [Required]
    [Display(Name = "Category Name")]
    public string CategoryName { get; set; }

    public ICollection<SubCategory> SubCategories { get; set; }
}

public class SubCategory
{
    public int Id { get; set; }

    [Required]
    [Display(Name = "SubCategory Name")]
    public string SubCategoryName { get; set; }

    public int CategoryID { get; set; }

    public Category Category { get; set; }
}

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