Subscribe to Youtube channel

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 method 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 needs to be 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 to fill dropdownlist with Json request using Jquery in MVC application.

Comments

Popular posts from this blog

Root your Gingerbread 2.3.4 android Mobile Phone

Implement Logging in CSV file using Nlog in .net core MVC application- part 2

Disable backspace key using Jquery

Devexpress Datebox date formatting in angular 6 with example

Implement Nlog in .Net core MVC application part 1

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

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

Angular User Session Timeout example step by step

Clone a generic list in C# using extension method