Populate Dropdown with jquery using JSON request in asp.net mvc3

In this Article i am going to demonstrate to fill the dropdownlist with jquery using JSON in asp.net mvc3. To achieve this task we need to write the following JavaScript code in view (.cshtml page)

@{
    ViewBag.Title = "Products";
}
<script type="text/javascript">

  jquery(document).ready(function () {
        jquery("ddlCategory").change(function () {


            var idModel = jquery("#ddlCategory").val();
            jquery.getJSON("product/items/", { category: idModel },
                    function (carData) {
                        
                        var select =jquery("#ddlitems");
                        select.empty();
                        select.append($('<option/>', {
                            value: 0,
                            text: ""


                        }));
                        jquery.each(carData, function (index, itemData) {

                            select.append(jquery('<option/>', {
                                value: itemData.Value,
                                text: itemData.Text
                            }));

                            
                        });
                    });

        
        })

    })
</script>
@Html.DropDownList("ddlCategory", new SelectList(new string[] { "Select", "CategoryA", "Category2" }.ToList(), "Select"))
@Html.DropDownList("ddlitems")


Above code having two dropdownlist one is for category and second is for items. The logic behind above code is to fill items as per category selected above. I have used jquery change methode to fill items on change of category. On change the JSON request will be sent back to server and on response from server the items populated in items dropdownlist

in controller following code need to write

  [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult Items(string category)
        {

            var result = DB.items.Where(ce=>ce.category==category);
            var itemtdata = result.Select(m => new SelectListItem()
            {
                Value = m.itemid,
                Text = m.itemname
            }
                );

            return Json(itemtdata, JsonRequestBehavior.AllowGet);

        }

I hope that this Article help you on fill dropdown on Json request using Jquery in MVC application

Comments

Popular posts from this blog

Restore the lost focus of Auto post back controls in asp.net update Panel control

Clone a generic list in C# using extension method

Add Comma automatically while entering amounts in textbox using Javascript

Disable backspace key using Jquery

Step by step migration of ASP.NET Core 2.2 to 3.1

How to Import CSV File and bind csv file data to gridview in asp.net using c#

Source Code Beautifier And Format Source Code For Blogger and Websites

Remove Owin from MVC 5 Application and use asp.net custom forms authentication

All about the IEnumerable VS IQueryable in c#