欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解ASP.NET MVC之下拉框绑定四种方式

程序员文章站 2022-06-09 10:14:18
前言 上两节我们讲了文件上传的问题,关于这个上传的问题还未结束,我也在花时间做做分割大文件处理以及显示进度的问题,到时完成的话再发表,为了不耽误学习mvc其他内容的计...

前言

上两节我们讲了文件上传的问题,关于这个上传的问题还未结束,我也在花时间做做分割大文件处理以及显示进度的问题,到时完成的话再发表,为了不耽误学习mvc其他内容的计划,我们今天开始好好讲讲关于mvc中下拉框中绑定枚举的几种方式。

话题引入

一般在下拉框中绑定数据的话,分为几种情况。

(1)下拉框中的数据是写死的,我们直接给出死代码即可。

(2)下拉框中的数据从数据库中读取出来,从而进行显示。

(3)下拉框中直接用枚举显示。

(4)下拉框中一个选择的值改变另外一个下拉框中的值。

关于下拉框中绑定大概就是以上四种方式,接下来我们一一来破解,我们样式利用bootstrap来表示,顺便也温习温习bootstrap。

下拉框硬编码【一】

我们在控制器中给出如下数据并利用viewbag来进行传递

   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" })

下面我们来看看效果:

详解ASP.NET MVC之下拉框绑定四种方式

下拉框读取数据库【二】

这个要读取数据库,我们就给出一个类测试就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" })

看看效果:

详解ASP.NET MVC之下拉框绑定四种方式

中 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" })

继续看看成果:

详解ASP.NET MVC之下拉框绑定四种方式

下拉框绑定枚举【三】(二)

 利用扩展方法  @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>

我们看看结果

详解ASP.NET MVC之下拉框绑定四种方式

下拉框选择则另一个下拉框对应改变 【四】

此例最合适的例子莫过于省市选择的案例。我们一起来看看。

(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));
     });
    }
   });
  }

我们来看看整个过程:

详解ASP.NET MVC之下拉框绑定四种方式

结语

对于下拉框绑定基本上已全部囊括进去,以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。