当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET MVC下拉框联动实例解析

ASP.NET MVC下拉框联动实例解析

2017年12月12日  | 移动技术网IT编程  | 我要评论

挑染,桥式工程塑料拖链,37wan大裁决

两个dropdownlist的联动,选择其中一个dropdownlist,然后加载数据到另外的一个dropdownlist上          
这里,我打算实现的需求是:有两个dropdownlist,一个默认加载所有的省份数据,然后,当我选择省份的时候,把对应的市的数据,绑定到另外一个dropdownlist上面,即实现了联动。
好了,这里不打算使用ef了,换用ado.net。首先新建好数据库,表:

use master 
go 
if exists (select * from sysdatabases where name='myaddressdb' )
drop database myaddressdb
go 
create database myaddressdb
go 
use myaddressdb
go 

if exists (select * from sysobjects where name='province')
drop table province
go
--省份表 
create table province
(
provinceid int identity(1,1) primary key,
provincename nvarchar(50) not null
)


if exists (select * from sysobjects where name='city')
drop table city
go
--省份表 
create table city
(
cityid int identity(1,1) primary key,
cityname nvarchar(50) not null,
provinceid int references dbo.province(provinceid) not null
)


--插入测试语句:【在网上找了一个省市数据库,把里面的数据导入我当前数据库中】
--开始
insert into dbo.province
select provincename from temp.dbo.s_province

insert into dbo.city
 ( cityname, provinceid )
 select cityname, provinceid from temp.dbo.s_city
--结束

--测试插入成功与否
--select * from dbo.province
--select * from dbo.city 

然后新建一个空白的mvc项目,在model文件夹下,添加两个实体: 

using system;
using system.collections.generic;
using system.linq;
using system.web;

namespace jsondatainmvc.models
{
 public class province
 {
 public int provinceid { get; set; }

 public string provincename { get; set; }
 }
} 

using system;
using system.collections.generic;
using system.linq;
using system.web;

namespace jsondatainmvc.models
{
 public class city
 {
 public int cityid { get; set; }

 public string cityname { get; set; }

 public int provinceid { get; set; }

 }
} 

然后在根目录下,新建一个文件夹dboperator,在里面新建一个addresshelper类 

addresshelper类中的代码: 

using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.configuration;
using jsondatainmvc.models;
using system.data;
using system.data.sqlclient;

namespace jsondatainmvc.dboperator
{
 public class addresshelper
 {
 
 /// <summary>
 /// 连接字符串
 /// </summary>
 public string connectionstring
 {
  get 
  {
  return configurationmanager.connectionstrings["dbconnectionstring"].connectionstring;
  }
 }

 /// <summary>
 /// 获取所有的省份
 /// </summary>
 /// <returns></returns>
 public list<province> getallprovince()
 {
  list<province> lstprovince = new list<province>();
  string sql = @"select * from dbo.province";

  //ado.net连接方式访问数据库
  //1.创建连接对象[连接字符串]
  sqlconnection conn = new sqlconnection(connectionstring);

  //2.创建命令对象
  sqlcommand cmd = new sqlcommand();
  cmd.commandtext = sql;
  cmd.commandtype = commandtype.text;
  cmd.connection = conn;

  //3.打开连接
  conn.open();

  //4.发送命令
  sqldatareader reader= cmd.executereader();

  //5.处理数据
  while (reader.read())
  {
  lstprovince.add(new province()
  {

   provinceid =convert.toint32( reader["provinceid"]),
   provincename = reader["provincename"].tostring()
  });
  }

  //6.关闭连接
  conn.close();
  reader.close();

  return lstprovince;

 }


 /// <summary>
 /// 通过provinceid获取市的数据
 /// </summary>
 /// <param name="id"></param>
 /// <returns></returns>
 public list<city> getcitylistbyprovinceid(int id)
 {
  dataset ds = new dataset();
string sql = @"select cityid,cityname from dbo.city where provinceid=@provinceid";

  //ado.net非连接方式访问数据库

  //1.创建连接对象
  sqlconnection conn = new sqlconnection(connectionstring); 
        //2.创建数据适配器对象
          sqldataadapter sda = new sqldataadapter(sql,conn);//这里还真必须这样写。不能像下面的两条注释语句那样写。
         //sda.selectcommand.connection = conn;
        //sda.selectcommand.commandtext = sql;
         sda.selectcommand.commandtype = commandtype.text;
  sda.selectcommand.parameters.addwithvalue("@provinceid", id);//参数设置别忘了
  //3.打开连接【注意,非链接模式下,连接的打开关闭,无所谓,不过还是打开好点。规范化】
  conn.open();

  //4.发送命令
  sda.fill(ds);

  //5.处理数据

  //6关闭连接【【注意,非链接模式下,连接的打开关闭,无所谓,不过还是打开好点。规范化】】
  conn.close();

  return datatabletolist<city>.converttomodel(ds.tables[0]).tolist<city>();
 }
 }
} 

datatable转list,我在网上找了一个帮助类: 

using system;
using system.collections.generic;
using system.data;
using system.linq;
using system.reflection;
using system.web;

namespace jsondatainmvc.dboperator
{
 public static class datatabletolist<t> where t : new()
 {
 public static ilist<t> converttomodel(datatable dt)
 {
  //定义集合
  ilist<t> ts = new list<t>();
  t t = new t();
  string tempname = "";
  //获取此模型的公共属性
  propertyinfo[] propertys = t.gettype().getproperties();
  foreach (datarow row in dt.rows)
  {
  t = new t();
  foreach (propertyinfo pi in propertys)
  {
   tempname = pi.name;
   //检查datatable是否包含此列
   if (dt.columns.contains(tempname))
   {
   //判断此属性是否有set
   if (!pi.canwrite)
    continue;
   object value = row[tempname];
   if (value != dbnull.value)
    pi.setvalue(t, value, null);
   }
  }
  ts.add(t);
  }
  return ts;
 }
 }
} 

创建province控制器: 

using jsondatainmvc.dboperator;
using jsondatainmvc.models;
using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.mvc;

namespace jsondatainmvc.controllers
{
 public class provincecontroller : controller
 {
 private addresshelper db;
 public provincecontroller()
 {
  db = new addresshelper();
 }
 // get: province
 public actionresult index()
 {
  list<province> lstprovince= db.getallprovince();

  viewbag.listprovince = lstprovince;

  return view();
 }
 }
} 

对应的index视图: 

@using jsondatainmvc.models
@{
 viewbag.title = "index";
 list<province> lstprovince = viewbag.listprovince as list<province>;
}

<h2>provinceindex</h2>

<label>省份:</label>
<select id="myprovince">
 @foreach (var item in lstprovince)
 {
 <option value="@item.provinceid">@item.provincename</option>
 }
</select> 

修改一下,默认的路由, 

 public static void registerroutes(routecollection routes)
 {
  routes.ignoreroute("{resource}.axd/{*pathinfo}");

  routes.maproute(
  name: "default",
  url: "{controller}/{action}/{id}",
  defaults: new { controller = "province", action = "index", id = urlparameter.optional }
  );
 } 

先来看下阶段性的成果:运行程序: 

看,这样就加载了所有的省份数据,现在我们要进一步实现,选择一个省份的时候,加载数据到另外一个下拉框中。
修改控制器,添加一个方法: 

using jsondatainmvc.dboperator;
using jsondatainmvc.models;
using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.mvc;

namespace jsondatainmvc.controllers
{
 public class provincecontroller : controller
 {
 private addresshelper db;
 public provincecontroller()
 {
  db = new addresshelper();
 }
 // get: province
 public actionresult index()
 {
  list<province> lstprovince= db.getallprovince();

  viewbag.listprovince = lstprovince;

  return view();
 }

 public jsonresult getallcitybyprovinceid(int id)
 {
  list<city> lstcity= db.getcitylistbyprovinceid(id);
  return json(lstcity, jsonrequestbehavior.allowget);
 }
 }
} 

index视图中: 

@using jsondatainmvc.models
@{
 viewbag.title = "index";
 list<province> lstprovince = viewbag.listprovince as list<province>;
}

<h2>provinceindex</h2>

<label>省份:</label>
<select id="myprovince">
 @foreach (var item in lstprovince)
 {
 <option value="@item.provinceid">@item.provincename</option>
 }
</select>
<br/>
<hr />
<label>城市:</label>
<select id="mycity">

</select>
<script src="~/scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
 $(document).ready(function () {
 $("#myprovince").change(function () {
  //获取省份的id
  var provinceid = $("#myprovince").val();
  
  //获取城市
  var mycity=$("#mycity");

  //加入测试代码
  debugger;

  $.ajax({
  url: "/province/getallcitybyprovinceid/" + provinceid,
  type: "post",
  datatype: "json",
  contenttype: "application/json",
  success: function (result) {
   var myhtml = "";
   mycity.html("");//赋值之前先清空
   $.each(result, function (i, data) {
   myhtml += "<option value=" + data.cityid + ">" + data.cityname + "</option>";

   });
   mycity.append(myhtml);
  },
  error: function (result) {
   alert(result.responsetext);
  }

  });


 })

 })
</script> 

好了,弄好之后,运行程序: 
选择一个省份,对应的市的信息就被我们查出来了,绑定到另外的市的下拉框中了。 

总结:这篇文章,虽然基础,但是很重要,平时开发中,遇到很多这样的场景。 
还有就是ef用多了,ado.net也不能忘记。 
连接模式和非链接模式查询数据库6个步骤,牢记心中。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网