Need expected Output in MVC

Analyst_SQL 3,551 Reputation points
2023-03-07T07:52:40.0133333+00:00

I have table below

Create  table #Sections (SecID int,SecName varchar(50))

Insert into #Sections values (1,'Brand')
Insert into #Sections values (2,'Shirst')

Create table #Category (Cat Int, Cat_Name varchar(50))

Insert into #Category values (11,'Amazon')
Insert into #Category values (12,'WalMart')

Create table #itemMasterFile (Codeitem int,Descriptionitem varchar(50),SecID int,Cat Int)

Insert into #itemMasterFile values (1001,'Trouser',2,12)
Insert into #itemMasterFile values (1002,'Jeans',1,11)

I want , above value get populate on dropdownlist,then on #itemMasterFile change in dropdown list ,then relevent data get populate in #Sections and #Category dropdownlist like below,

means that if i select Jean ,then SecID and Cat get from relevent table.

User's image

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,365 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,484 questions
0 comments No comments
{count} votes

Accepted answer
  1. Lan Huang-MSFT 27,796 Reputation points Microsoft Vendor
    2023-03-08T05:21:56.2166667+00:00

    Hi @Analyst_SQL ,

    You can get CodeItem through the jQuery Onchange event, and then obtain Secid according to Linq query.

    public JsonResult GetSections(int itemId)
            {       
               int Secid = DB.ItemMasterFiles.First(a => a.CodeItem == itemId).SecID;
               var STATUS_LIST = (from s in DB.Sections
                                   where s.SecID ==Secid
                                   select new SelectListItem()
                                   {
                                       Text = s.SecName,
                                       Value = s.SecID.ToString(),
                                   }).ToList();
                return Json(STATUS_LIST, JsonRequestBehavior.AllowGet);
            }
    

    I wrote a demonstration, you can refer to:

    @model MVC418.Models.CascadingModel
    
    @{
        ViewBag.Title = "Home Page";
    }
    
    <body>
        <div class="col-lg-8">
            <div class="card card-default mb-5">
                <div class="card-header">Designation Form</div>
                <div class="card-body">
                    @using (Html.BeginForm("index", "home", FormMethod.Post))
                    {
                        @Html.AntiForgeryToken()
                        <div class="form-horizontal">
                            <hr />
                            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                            <div class="form-group">
                                @Html.LabelFor(model => model.CodeItem, "Select Item", htmlAttributes: new { @class = "control-label col-md-6" })
                                <div class="col-md-10">
                                    @Html.DropDownList("codeitem", (SelectList)ViewBag.Codeitem, "Select", htmlAttributes: new { @class = "form-control", @id = "select2-1" })
    
                                    @Html.ValidationMessageFor(model => model.CodeItem, "", new { @class = "text-danger" })
                                </div>
                            </div>
                            <div class="form-group">
                                @Html.LabelFor(model => model.SecId, "Select Section", htmlAttributes: new { @class = "control-label col-md-6" })
                                <div class="col-md-10">
                                    <div id="123">
                                        @Html.DropDownList("SecId", null, "Select Section", htmlAttributes: new { @class = "form-control", @id = "select2-2" })
    
                                    </div>
    
                                    @Html.ValidationMessageFor(model => model.SecId, "", new { @class = "text-danger" })
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-md-offset-2 col-md-10">
                                    <input type="submit" value="Create" class="btn btn-default" />
                                </div>
                            </div>
                        </div>
                    }
                    <div>
                        @Html.ActionLink("Back to List", "AllDesignation")
                    </div>
                </div>
            </div>
        </div>
    </body>
    
    
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#select2-1").change(function () {
                var itemId = $("#select2-1").val();
                if (itemId != "") {
                    GetSections(itemId);
                }
                else {
                    $("#select2-2").empty();
    
                }
              
            });
        });
        function GetSections(itemId) {
            $.ajax({
                async: true,
                type: 'GET',
                dataType: 'JSON',
                contentType: 'application/json; charset=utf-8',
                url: '/Home/GetSections',
                data: { itemId: itemId },
                success: function (data) {                
                 
                    $('#select2-2').empty();
                    $(data).each(function (index, item) {
                        $('#select2-2').append($('<option/>', { value: item.Value, text: item.Text }))
                    })                         
                },
                error: function () {
                    alert("There is some problem to get.");
                }
            });
        }
    
    </script>
    
    
     public ActionResult Index()
            {
                var secID = 0;
                ViewBag.secID = new SelectList(DB.Sections.Where(bt => bt.SecID > secID), "SecID", "SecName", "0");
                var codeItem = 0;
                ViewBag.codeItem = new SelectList(DB.ItemMasterFiles.Where(bt => bt.CodeItem > codeItem), "Codeitem", "Descriptionitem", "0");     
                return View();
            }
          
            [HttpGet]
            public JsonResult GetSections(int itemId)
            {       
               int Secid = DB.ItemMasterFiles.First(a => a.CodeItem == itemId).SecID;
               var STATUS_LIST = (from s in DB.Sections
                                   where s.SecID ==Secid
                                   select new SelectListItem()
                                   {
                                       Text = s.SecName,
                                       Value = s.SecID.ToString(),
                                   }).ToList();
                return Json(STATUS_LIST, JsonRequestBehavior.AllowGet);
            }
    
     public class itemMasterFile
        {
            [Key]
            public int SecID { get; set; }        
            public int CodeItem { get; set; }
            public string Descriptionitem { get; set; }     
        }
        public class Sections
        {
            [Key]
            public int SecID { get; set; }
            public string SecName { get; set; }
        }
        
        public class CascadingModel
        {       
            public List<Sections> Sections { get; set; }
            public List<itemMasterFile> ItemMasterFiles { get; set; }
            public int? SecId { get; set; }
            public int? CodeItem { get; set; }
        }
    

    3

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Nelson Murithi Kanathi 0 Reputation points
    2023-03-07T10:16:31.11+00:00

    Hello Akhter,

    You should use JQuery Onchange event on the #itemMasterFile field then fetch the related categories using an AJAX request. You can do it like below:

    I assume your dropdown is like this:

    <select asp-for="itemMasterFile" asp-items="ViewBag.itemMasterFiles"> 
    </select>
    
    <select asp-for="Sections" >
    </select>
    
    

    In the view or in a separate javascript file use:

    //Subscribe to jQuery change event - called when the value in itemmasterfile dropdown changes
    $("#itemMasterFile").change(function () 
    {
        var selectedItem = $(this).val();    
        getRelatedData(selectedItem);
    });
    
    
    //function to make the ajax call
    function getRelatedData(itemid) 
    {
        $.ajax({
            url: '/ControllerName/ActionName',
            type: 'GET',
            data: {selectedid : itemid },
            dataType: 'json',
            success: function (data) {
                var options = '<option value="0">--Select Sections--   </option>';
    //loop through each collection of sections
                $.each(data, function () {
                    options += '<option value="' + this.id + '">' +
                        this.name + '</option>';
                });
    //append the select options to the Sections select box
                $("#Sections").html(options);          
            },
            error: function (xhr, status, error) {            
                alert(xhr.responseText);
    
            },
            failure: function (xhr, status, error) {           
                alert(xhr.responseText);
    
            }
        });
    }
    

    In your controller make sure you have a method to return Sections by selectedId.

    Incase of any inquiry feel free to comment or email me at nelsonkanathi1@outlook.com