Click here to Skip to main content
15,922,155 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi
I have this web page with multiple categories. I have build the table with a self reference table in entity framework, so the user can create categories with multiple children.

I want an dropdown list with categories and when you click on the dropdown menu, I get the value and send the value with ajax to the controller and check if this category have children and populate this in an new dropdown list.

I have done this function, but how do I make a function that populate a new dropdownlist everytime when I click in the dropdown list with out hardcode the dropdown list??

This is my view code :

C#
@Html.DropDownList("CategoryId", ViewBag.CategoryId as SelectList, "Select a Category", new { id = "CategoryId", @class = "form-control" })<br />

        @Html.DropDownList("Subcategory", new SelectList(string.Empty, "Value", "Text"), "Please select a Subcategory", new { @class = "form-control" })


The ajax call in the view :

JavaScript
 //Run Jquery script
jQuery(document).ready(function ($) {
   //Dropdownlist Selectedchange event
    $("#CategoryId").change(function () {
        //Take the Id from the dropdown list when selected an item
        var id = $(this).find(":selected").val()
        var catId = { "catId": id }
        //Make the dropdown empty
        $("#Subcategory").empty();
        //Send the information to the controller
        $.ajax({
            type: 'POST',
            url: '@Url.Action("CategoryList", "Manage")', // we are calling json method

            data: JSON.stringify(catId),

            contentType: 'application/json; charset-utf-8',
            //here we are get value of selected item and passing same value
            // to input to the json method CategoryList.
            success: updateDropdown
        });
    });



});
var updateDropdown = function (subcategories) {

    if (subcategories.length == 0) {
        console.log("NO DATA!")
    }
    else {
        var ddl = $('#Subcategory');
        $.each(subcategories, function (index, item) {
            $(document.createElement('option'))
            .attr('value', this.Id)
            .text(item.Text)
            .appendTo(ddl);


            //$("#Subcategory").append('<option value="' + item.Value + '">' +
            //      item.Text + '</option>');

        });
    }
};


C#
[HttpPost]
       public JsonResult CategoryList(int catId)
       {

           var subcategories = (from s in db.Categories where s.ParentCategoryId == catId select new SelectListItem {
               Text = s.Name, Value = s.ParentCategoryId.ToString()

           });

               //If the category have children do this
               return Json(subcategories, JsonRequestBehavior.AllowGet);




       }


Hope someone could get me in the right direction
Posted
Comments
Krunal Rohit 5-Nov-15 9:43am    
Don't you mean cascading dropdowns ?
And you need to use the partial views.

-KR
tina_overgaard 5-Nov-15 9:51am    
yes cascading dropdowns, then I load the partial view everytime I need an new dropdown menu??
Krunal Rohit 5-Nov-15 9:53am    
Yes, you need one another dropdown list.

-KR
tina_overgaard 5-Nov-15 10:58am    
When I click on the first dropdown, I send the values to the CategoryList and return the json object again to the ajax succes call and inside where I add value to the dropdown I do it to a partial view?

1 solution

Try to build the dropdown list items on ajax success function call:
JavaScript
$("#CategoryId").change(function () {
var id = $(this).val();
$.ajax({
    type: 'GET',
    url: '@Url.Action("CategoryList", "Manage")', // we are calling json method
    data: {catId: id},
    contentType: 'application/json; charset-utf-8',
    success: function(data) {
            $("#Subcategory").empty();
            $.each(data, function (id, option) {
                $("#Subcategory").append($('<option></option>').val(option.SubCategoryId).html(option.SubCategoryNme));
            });
        }
    });
});

This better be a GET request. Change it in a controller.
But as I said in a comment, use partial views and load the partial view on each call, that will refresh your dropdown and you don't have to build that HTML. :)

-KR
 
Share this answer
 
Comments
tina_overgaard 5-Nov-15 13:56pm    
How to I load this partial view inside my ajax call?
Krunal Rohit 5-Nov-15 23:32pm    
Your action method will return the partialview with the data. And that partial view is already mapped within the razor page having dropdown list. Now, on ajax success call, instead of creating ddl with HTML, you'll return the html for that partial view.

<div id="ddl_pv">
// your partial view with ddl
</div>

success: function(data)
{
$("#ddl").html(data);
}

-KR

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900