неділя, 9 жовтня 2011 р.

MVC: Cascading Dropdown

Action Methods:
[HttpPost]
public JsonResult GetCategories()
{
    Thread.Sleep(1000);

    return Json(categoriesList);
}

[HttpPost]
public JsonResult GetProducts(int? category)
{
    Thread.Sleep(1000);

    var list = category.HasValue ? productsList.Where(x => x.CategoryId == category).ToList() : productsList;

    return Json(list);
}
HTML:
<lable for="category">Category</lable>
<select id="category" name="category">
<option value="-1">Select...</option>
@foreach (var item in Model)
{
    <option value="@item.Id">@item.Title</option>
}
</select>
<lable for="product">Product</lable>
<select id="product" name="product">
    <option value="-1">Select cetegory...</option>
</select>
Script:
$(function () {
        var categories = $('#category');
        var products = $('#product');

        products.change(function () {
            console.log(products.val());
        });

        categories.change(function () {
            var id = categories.val();

            if (id != -1) {
                products.empty();
                products.append($('<option/>', {
                    value: -1,
                    text: "Loading..."
                }));

                $.ajax({
                    type: 'POST',
                    url: "/Products/GetProducts",
                    data: { category: id },
                    success: function (resp) {
                        var items = eval(resp);

                        products.empty();
                        products.append($('<option/>', {
                            value: -1,
                            text: "Select product..."
                        }));

                        $.each(items, function (index, item) {
                            products.append($('<option/>', {
                                value: item.Id,
                                text: item.Title
                            }))
                        });
                    },
                    error: function () {
                        console.log('Error');
                        console.log(arguments);
                    }
                });
            } else {
                products.empty();
                products.append($('<option/>', {
                    value: -1,
                    text: "Select cetegory..."
                }));
            }
        });
    });

Немає коментарів:

Дописати коментар