三级级联下拉列表

时间:2014-01-10 19:20:58

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我是编程的初学者,在过去的两天里,我正在寻求帮助:)

我正在构建一个mvc 4应用程序,我有一个部门列表的部分视图,当您选择部门时,您可以在浏览视图的下拉列表中看到该特定部门的项目类型。

我想要做的是浏览视图中的另一个下拉列表,它将根据所选部门和项目类型显示项目。

所以这是我的代码:

查看:

@using (Html.BeginForm("Browse", "Bookings", FormMethod.Post, new { id = "TypeItemFormID", data_itemsListAction = @Url.Action("ItemsList") }))
{
<fieldset>
    <legend> Type/Item</legend>
    @Html.DropDownList("department", ViewBag.ItemTypesList as SelectList, "Select a Type", new {id="ItemTypeID"})
    <div id="ItemsDivId">
        <label for="Items">Items </label>
        <select id="ItemsID" name="Items"></select>
    </div>
    <p>
        <input type ="submit" value="Submit" id="SubmitID" />
    </p>
 </fieldset>
}
<script src ="@Url.Content("~/Scripts/typeItems.js")"></script>

控制器:

public class BookingsController : Controller
    {

        private BookingSystemEntities db = new BookingSystemEntities();
        //
        // GET: /Bookings/

        public ActionResult Index()
        {
            ViewBag.Message = "Select your Department";
            var departments = db.Departments.ToList();
            return View(departments);
        }

        public ActionResult Browse(string department, string ID)
        {

            ViewBag.Message = "Browse for Equipment";

           var departments = db.Departments.Include("Items").Single(i => i.DepartmentName == department);

           ViewBag.ItemTypesList = GetItemTypeSelectList(department);

           return View();

        }

        public ActionResult Details(int id)
        {
            var item = db.Items.Find(id);

            return View(item);
        }

        //
        // GET: /Home/DepartmentMenu
        [ChildActionOnly]
        public ActionResult DepartmentMenu()
        {
            var departments = db.Departments.ToList();
            return PartialView(departments);
        }


        public SelectList GetItemTypeSelectList(string department)
        {
            var departments = db.Departments.Include("Items").Single(i => i.DepartmentName == department);
            List<SelectListItem> listItemTypes = new List<SelectListItem>();
            foreach (var item in departments.Items.Select(s => s.ItemType.ItemTypeName).Distinct())
            {
                listItemTypes.Add(new SelectListItem
                {
                    Text = item,
                    Value = item,
                }

                     );
            }

            return new SelectList(listItemTypes.ToArray(),
                                "Text",
                                "Value");

        }

        public ActionResult ItemsList(string ID)
        {
            string Text = ID;
            var items = from s in db.Items
                        where s.ItemType.ItemTypeName == Text
                        select s;

            if (HttpContext.Request.IsAjaxRequest())
                return Json(new SelectList(
                                items.ToArray(),
                                "ItemId",
                                "ItemName")
                           , JsonRequestBehavior.AllowGet);

            return RedirectToAction("Browse");
        } 


    }

Javascript:

$(function () {

    $('#ItemsDivId').hide();
    $('#SubmitID').hide();

    $('#ItemTypeID').change(function () {
        var URL = $('#TypeItemFormID').data('itemsListAction');
        $.getJSON(URL + '/' + $('#ItemTypeID').val(), function (data) {
            var items = '<option>Select a Item</option>';
            $.each(data, function (i, item) {
                items += "<option value='" + item.Value + "'>" + item.Text + "</option>";
                // state.Value cannot contain ' character. We are OK because state.Value = cnt++;
            });
            $('#ItemsID').html(items);
            $('#ItemsDivId').show();

        });
    });

    $('#ItemsID').change(function () {
        $('#SubmitID').show();
    });
});

最后我的模特:

 public class Department
    {
        public int DepartmentId { get; set; }

        [DisplayName("Department")]
        public string DepartmentName { get; set; }

        public List<Item> Items { get; set; }

    }

public class ItemType
    {
        public int ItemTypeId { get; set; }

        [DisplayName("Type")]
        public string ItemTypeName { get; set; }

        [DisplayName("Image")]
        public string ItemTypeImage { get; set; }

        public List<Item> Items { get; set; }

    }

 public class Item
    {
        public int ItemId { get; set; }

        [DisplayName("Name")]
        public string ItemName { get; set; }

        [DisplayName("Description")]
        public string ItemDescription { get; set; }

         [DisplayName("Ref Code")]
        public string ItemReferenceCode { get; set; }

        [ForeignKey("ItemType")]
        public int ItemTypeId { get; set; }
        public virtual ItemType ItemType { get; set; }

        [ForeignKey("Department")]
        public int DepartmentId { get; set; }
        public Department Department { get; set; }

        [DisplayName("Computer Location")]
        public string ComputerLocation { get; set; }

        [DisplayName("Author Name")]
        public string AuthorName { get; set; }

        [DisplayName("Published Year")]
        public string PublishedYear { get; set; }

    }

1 个答案:

答案 0 :(得分:2)

以下是我将如何完成这样的事情。这不是唯一的方法。

 $('#ItemTypeID').on('change', function() {
        $.ajax({
            type: 'POST',
            url: '@Url.Action("GetItemTypeForm")',
            data: { itemTypeId: $('#ItemTypeID').val() },
            success: function(results) {
                var options = $('#ItemTypeFormId');
                options.empty();
                options.append($('<option />').val(null).text("- Select an Item Type  -"));
                $.each(results, function() {
                    options.append($('<option />').val(this.ItemTypeFormId).text(this.Value));
                });
            }
        });
    });

然后你有一个看起来像这样的控制器。

[HttpPost]
    public JsonResult GetItemTypeForm(string itemTypeId)
    {
        //pseudo code
        var data = Repostitory.GetData(itemTypeId) 

        return Json(data);
    }