[MVC4-基礎] 連動DropDownList - 使用jQuery、JSON

剛開始學MVC4,以下是一些基礎的學習筆記!


先展示一下結果:

1.選擇申請部門

2.選好後申請部門鎖住防止USER修改並載入該部門所擁有的設備類型


一、資料庫

dept

mf_fx

 

二、View (Index.cshtml)

@model IEnumerable<LES.Models.Repair>

@{
    ViewBag.Title = "Index";
}
<script type="text/javascript">
    $(document).ready(function () {
        $(".DropDownList").append("<option value='Value'>請選擇</option>"); //預設都加入「請選擇」
        $(".DropDownList").change(function () {
            //讓下拉選單選中即關閉
            $(this).attr("disabled", true);

            //取出元素ID
            var id = $(this).attr('id');

            //根據選中的元素執行相對應的動作
            switch (id) {
                case "dept": {
                    //選擇部門後把設備類型資料載入
                    $(function () {
                        $.getJSON("/Repair/GetDeviceType?dept=" + dept.value, null, function (data) {//向Controller取得GetDeviceType資料

                            $.each(data, function (i, itemvalue) {//循環加入item

                                $("#deviceType").append(

                                    $("<option></option>").val(itemvalue.Value).html(itemvalue.Text))

                            });
                        });
                    });
                    break;
                }

                case "deviceType": {
                    //選擇設備類型後把設備編號資料載入
                    $(function () {
                        $.getJSON("/Repair/GetDeviceId?dept=" + dept.value + "&type=" + deviceType.value, null, function (data) {//向Controller取得GetDeviceId資料

                            $.each(data, function (i, itemvalue) {//循環加入item

                                $("#deviceId").append(

                                    $("<option></option>").val(itemvalue.Value).html(itemvalue.Text))

                            });
                        });
                    });
                    break;
                }
            }
            
        });
    });

    $(function () {
        $.getJSON("/Repair/GetDept", null, function (data) {//向Controller取得GetDept資料

            $.each(data, function (i, itemvalue) {//循環加入item

                $("#dept").append(

                    $("<option></option>").val(itemvalue.Value).html(itemvalue.Text))

            });
        });
    });
</script>


<h2>維修申請單</h2>

<p>
    
    @Html.Label("dept","申請部門")
    <select class="DropDownList" id="dept" name="dept"></select>
    <br />

    @Html.Label("deviceType","設備類型")
    <select class="DropDownList" id="deviceType" name="deviceType"></select>
    <br />
    
</p>

 

三、Controller (RepairController.cs)

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LES.Models;
using System.Data.SqlClient;
using System.Configuration;

namespace LES.Controllers
{
    public class RepairController : Controller
    {
        string ErpString = ConfigurationManager.ConnectionStrings["ERPConnection"].ConnectionString; 

        //
        // GET: /Repair/

        public ActionResult Index()
        {

            SqlConnection DbErp = new SqlConnection(ErpString); //創建資料庫連線
            SqlCommand cmd = new SqlCommand("select dep,name from dept",DbErp); //輸入SQL命令
            DbErp.Open(); //開啟資料庫連線

            var reader = cmd.ExecuteReader(); //取出結果集

            List<SelectListItem> depts = new List<SelectListItem>();

            while(reader.Read()){ //逐筆讀出資料寫入List
                //(0)=dep ; (1)=name
                depts.Add(new SelectListItem { Text = reader.GetString(1), Value = reader.GetString(0)});
            }

            DbErp.Close(); //關閉資料庫連線

            ViewBag.DeptType = depts;

            return View();
        }

        // GET: /Repair/GetDept
        public JsonResult GetDept()
        {
            SqlConnection DbErp = new SqlConnection(ErpString); //創建資料庫連線
            SqlCommand cmd = new SqlCommand("select dep,name from dept", DbErp); //輸入SQL命令
            DbErp.Open(); //開啟資料庫連線

            var reader = cmd.ExecuteReader(); //取出結果集

            List<SelectListItem> depts = new List<SelectListItem>();

            while (reader.Read())
            { //逐筆讀出資料寫入List
                //(0)=dep ; (1)=name
                depts.Add(new SelectListItem { Text = reader.GetString(1), Value = reader.GetString(0) });
            }

            DbErp.Close(); //關閉資料庫連線

            return this.Json(depts, JsonRequestBehavior.AllowGet);
        }

        // GET: /Repair/GetDeviceType?dept=部門代號
        public JsonResult GetDeviceType(string dept)
        {
            SqlConnection DbErp = new SqlConnection(ErpString); //創建資料庫連線
            DbErp.Open(); //開啟資料庫連線
            SqlCommand cmd = DbErp.CreateCommand(); //創建命令物件
            cmd.CommandText = "select distinct name from mf_fx where dep = @dept"; //SQL語句
            cmd.Parameters.AddWithValue("dept", dept); //加入@dept參數      

            var reader = cmd.ExecuteReader(); //取出結果集

            List<SelectListItem> types = new List<SelectListItem>();

            while (reader.Read())
            { //逐筆讀出資料寫入List
                //(0)=name
                types.Add(new SelectListItem { Text = reader.GetString(0), Value = reader.GetString(0) });
            }

            DbErp.Close(); //關閉資料庫連線

            return this.Json(types, JsonRequestBehavior.AllowGet);
        }
    }
}

 


後來更新一下代碼,新的初始狀態如下:

 

posted @ 2013-08-19 15:30  Ren.Auxo  阅读(1802)  评论(0编辑  收藏  举报