ASP.NET MVC之下拉框綁定四種方式(十)

前言

上兩節咱們講了文件上傳的問題,關於這個上傳的問題還未結束,我也在花時間作作分割大文件處理以及顯示進度的問題,到時完成的話再發表,爲了避免耽誤學習MVC其餘內容的計劃,咱們今天開始好好講講關於MVC中下拉框中綁定枚舉的幾種方式。html

話題引入

通常在下拉框中綁定數據的話,分爲幾種狀況。ajax

(1)下拉框中的數據是寫死的,咱們直接給出死代碼便可。數據庫

(2)下拉框中的數據從數據庫中讀取出來,從而進行顯示。微信

(3)下拉框中直接用枚舉顯示。app

(4)下拉框中一個選擇的值改變另一個下拉框中的值。學習

關於下拉框中綁定大概就是以上四種方式,接下來咱們一一來破解,咱們樣式利用Bootstrap來表示,順便也溫習溫習Bootstrap。測試

下拉框硬編碼【一】

咱們在控制器中給出以下數據並利用ViewBag來進行傳遞ui

           ViewBag.hard_value = new List<SelectListItem>() { 
                new SelectListItem(){Value="0",Text="xpy0928"},
                new SelectListItem(){Value="1",Text="cnblogs"}
            };

在數據中進行以下綁定編碼

  @Html.DropDownList("hard-code-dropdownlist", new SelectList(ViewBag.hard_value, "Value", "Text"), new { @class = "btn btn-success dropdown-toggle form-control" })

下面咱們來看看效果:url

下拉框讀取數據庫【二】

這個要讀取數據庫,咱們就給出一個類測試就ok,並給出默認選中值,測試類:

        public class BlogCategory
        {
            public int CategoryId { get; set; }
            public string CategoryName { get; set; }

        }

綁定ViewBag傳值:

            //從數據庫中讀取
            var categoryList = new List<BlogCategory>() { 
                new BlogCategory(){CategoryId=1,CategoryName="C#"},
                new BlogCategory(){CategoryId=2,CategoryName="Java"},
                new BlogCategory(){CategoryId=3,CategoryName="JavaScript"},
                new BlogCategory(){CategoryId=4,CategoryName="C"}
            };
            var selectItemList = new List<SelectListItem>() { 
                new SelectListItem(){Value="0",Text="所有",Selected=true}
            };
            var selectList = new SelectList(categoryList, "CategoryId", "CategoryName");
            selectItemList.AddRange(selectList);
            ViewBag.database = selectItemList;

視圖稍加修改:

@Html.DropDownList("database-dropdownlist", ViewBag.database as IEnumerable<SelectListItem>, new { @class = "btn btn-success dropdown-toggle form-control" })

看看效果:

注意:上述視圖中 ViewBag.database 須要進行轉換不然出現以下錯誤:

 CS1973: 「System.Web.Mvc.HtmlHelper<dynamic>」沒有名爲「DropDownList」的適用方法,但彷佛有一個具備該名稱的擴展方法。擴展方法不能進行動態調度。請考慮強制轉換動態參數,或調用該擴展方法但不使用擴展方法語法。

下拉框綁定枚舉【三】(一)

 咱們一樣給出一個測試類:

        public enum Language
        {
            Chinese,
            English,
            Japan,
            Spanish,
            Urdu
        }

獲取枚舉值並綁定:

 ViewBag.from_enum = Enum.GetValues(typeof(Language)).Cast<Language>();

視圖給出:

  @Html.DropDownList("database-dropdownlist", new SelectList(ViewBag.from_enum), new { @class = "btn btn-success dropdown-toggle form-control" })

繼續看當作果:

下拉框綁定枚舉【三】(二)

 利用擴展方法  @Html.EnumDropDownListFor 來實現。接下來依次給出兩個類來進行演示:

    public class StudentModel
    {
        [Display(Name = "語言")]
        public ProgrammingLanguages Language { get; set; }
    }
    public enum ProgrammingLanguages
    {
        [Display(Name = "ASP.NET")]
        ASPNet,
        [Display(Name = "C# .NET")]
        CSharp,
        [Display(Name = "Java")]
        Java,
        [Display(Name = "Objective C")]
        ObjectiveC,
        [Display(Name = "Visual Basic .NET")]
        VBNet,
        [Display(Name = "Visual DataFlex")]
        VisualDataFlex,
        [Display(Name = "Visual Fortran")]
        VisualFortran,
        [Display(Name = "Visual FoxPro")]
        VisualFoxPro,
        [Display(Name = "Visual J++")]
        VisualJPlus
    }

在視圖中進行綁定:

   <div class="form-group">
        @Html.LabelFor(model => model.Language, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EnumDropDownListFor(model => model.Language, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Language, "", new { @class = "text-danger" })
        </div>
    </div>

咱們看看結果:

下拉框選擇則另外一個下拉框對應改變 【四】

此例最合適的例子莫過於省市選擇的案例。咱們一塊兒來看看。

(1)所屬省、市一級僱員類。

    public class Province
    {
        public int provinceId { get; set; }
        public string provinceName { get; set; }
        public string Abbr { get; set; }
    }
    public class City
    {
        public int CityId { get; set; }
        public string CityName { get; set; }
        public int provinceId { get; set; }
    }
    public class Employees
    {

        [Key]
        public int EmployeeId { get; set; }

        [Required, Display(Name = "僱員名字")]
        public string EmployeeName { get; set; }

        [Required, Display(Name = "地址")]
        public String Address { get; set; }

        [Required, Display(Name = "所屬省")]
        public int Province { get; set; }

        [Required, Display(Name = "所在城市")]
        public int City { get; set; }

        [Display(Name = "地區代碼")]
        public String ZipCode { get; set; }

        [Required, Display(Name = "聯繫號碼")]
        public String Phone { get; set; }
    }

(2)初始化數據

 List<Province> provinceList = new List<Province>() { 
                new Province(){provinceId=1,provinceName="湖南",Abbr="hunan_province"},
                new Province(){provinceId=2,provinceName="廣東",Abbr="guangdong_province"},
                new Province(){provinceId=3,provinceName="吉林",Abbr="jilin_province"},
                new Province(){provinceId=4,provinceName="黑龍江",Abbr="heilongjiang_province"}
            };

以及綁定ViewBag到下拉框和控制器上的方法:

        [HttpGet]
        public ActionResult Create()
        {

            ViewBag.ProvinceList = provinceList;
            var model = new Employees();
            return View(model);
        }

        [HttpPost]
        public ActionResult Create(Employees model)
        {
            if (ModelState.IsValid)
            {

            }
            ViewBag.ProvinceList = provinceList;
            return View(model);
        }

        public ActionResult FillCity(int provinceId)
        {
            var cities = new List<City>() {
             new City(){CityId=10,CityName="岳陽市",provinceId=1},
             new City(){CityId=10,CityName="深圳市",provinceId=2},
             new City(){CityId=10,CityName="吉林市",provinceId=3},
             new City(){CityId=10,CityName="哈爾濱市",provinceId=4}
            };
            cities = cities.Where(s => s.provinceId == provinceId).ToList();
            return Json(cities, JsonRequestBehavior.AllowGet);
        }

 (3)視圖展現

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>註冊僱員</h4>
            <div class="form-group">
                @Html.LabelFor(m => m.EmployeeName, new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.TextBoxFor(m => m.EmployeeName, new { @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.EmployeeName, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(m => m.Address, new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.TextBoxFor(m => m.Address, new { @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.Address, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(m => m.Province, new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownListFor(m => m.Province,
new SelectList(ViewBag.ProvinceList, "provinceId", "provinceName"),
                  "選擇所在省",
                  new { @class = "form-control", @onchange = "FillCity()" })
                    @Html.ValidationMessageFor(m => m.Province, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(m => m.City, new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownListFor(m => m.City,
           new SelectList(Enumerable.Empty<SelectListItem>(), "CityId", "CityName"),
                  "選擇所在市",
                  new { @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.City, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(m => m.ZipCode, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.TextBoxFor(m => m.ZipCode, new { @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.ZipCode, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(m => m.Phone, new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.TextBoxFor(m => m.Phone, new { @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.Phone, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-success" />
                    <a href="/Home/Employees" class="btn btn-warning">Cancel</a>
                </div>
            </div>
        </div>
    }

(4)根據省下拉框選擇到市下拉框腳本

       function FillCity() {
            var provinceId = $('#Province').val();
            $.ajax({
                url: '/Home/FillCity',
                type: "GET",
                dataType: "JSON",
                data: { provinceId: provinceId },
                success: function (cities) {
                    $("#City").html("");
                    $.each(cities, function (i, city) {
                        $("#City").append(
                            $('<option></option>').val(city.CityId).html(city.CityName));
                    });
                }
            });
        }

咱們來看看整個過程:

 

結語

 對於下拉框綁定基本上已所有囊括進去,不斷鑽研,不斷總結纔能有能力上更好的提高。但願對閱讀本文的你有所幫助,若是有幫助,不妨討打(乞討打賞)一下,1塊也是愛:)。

衷心感謝打賞者的厚愛以及點贊和評論的園友的支持!打賞時您能夠備註或聯繫告知我您但願下方出現的打賞者格式,再次表示感謝!
打賞者 打賞金額 打賞次數 打賞日期
支付寶:啓山 1.00 1 2016-04-24
微信:喝前搖一搖 5.00 1 2016-04-29
相關文章
相關標籤/搜索