asp.net mvc drop-down Box Linkage Case Analysis _ practical skills

Source: Internet
Author: User

Two DropDownList linkage, select one of the DropDownList, and then load the data onto another DropDownList            
Here, I intend to achieve the requirements are: There are two DropDownList, a default load all the province data, and then, when I choose the province, the corresponding city data, binding to another DropDownList above, namely realizes the linkage.
Well, here's no plan to use EF, swap ado.net. First create a good database, table:

Use master 
go 
IF EXISTS (SELECT * from sysdatabases WHERE name= ' myaddressdb ')
DROP DATABASE myaddressdb
Go 
CREATE DATABASE myaddressdb go to myaddressdb go to 

IF EXISTS (SELECT * from sysobjects WHERE name= ' Province ')
DROP table province
go
--province table 
CREATE table province
(
Provinceid INT IDENTITY (1,1) PRIMARY KEY,
provincename NVARCHAR not NULL
)


IF EXISTS (SELECT * from sysobjects WHERE n Ame= ' city ',
DROP table City
go
--province table 
CREATE table City
(
Cityid INT IDENTITY (1,1) PRIMARY KEY,
cityname NVARCHAR (m) not NULL,
provinceid INT REFERENCES dbo. Province (Provinceid) not NULL
)-


-Inserts a test statement: "Find a provincial and municipal database on the Internet, import the data into my current database"-
-start
INSERT INTO dbo. Province
SELECT provincename from Temp.dbo.S_Province

inserts into dbo. City
 (CityName, Provinceid)
 SELECT cityname, Provinceid from Temp.dbo.S_City
--end

--Test insert success or not
--select * FROM dbo. Province
--select * FROM dbo. City 

Then create a new blank MVC project, and add two entities under the Model folder:

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

Then in the root directory, create a new folder Dboperator, create a new Addresshelper class inside

Code in the Addresshelper class :

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>///connection string///
 ; public string ConnectionString {get {return configurationmanager.connectionstrings["dbconnectionstring"].
  ConnectionString; }///<summary>///get all provinces///</summary>///<returns></returns> public list<provinc
  E> getallprovince () {list<province> lstprovince = new list<province> (); String sql = @ "SELECT * FROM dbo.

  Province "; Ado.

  NET connection method to access the database//1. Create a Connection object [connection string] SqlConnection conn = new SqlConnection (ConnectionString);
  2. Create Command object SqlCommand cmd = new SqlCommand ();
  Cmd.commandtext = SQL;
  Cmd.commandtype = CommandType.Text; Cmd.

  Connection = conn; 3. Open Connection Conn.

  Open (); 4. Send command SqldatarEader reader= cmd.

  ExecuteReader (); 5. Process data while reader.  Read ()) {Lstprovince.add (new province () {Provinceid =convert.toint32 (reader["Provinceid"]), Provincename = reader["Provincename"].
  ToString ()}); //6. Closes the connection conn.
  Close (); Reader.

  Close ();

 return lstprovince; ///<summary>///obtains data///</summary>///<param name= "id" ></param>///via Provinceid ;returns></returns> public list<city> getcitylistbyprovinceid (int id) {DataSet ds = new DataSet (); str ing sql = @ "SELECT Cityid,cityname from dbo.

  City WHERE provinceid= @ProvinceID "; Ado. 
        NET connectionless Access database//1. Create a Connection object SqlConnection conn = new SqlConnection (ConnectionString); 2. Create a data adapter object SqlDataAdapter SDA = new SqlDataAdapter (sql,conn);//It must be written here.
         You cannot write like the following two comment statements. Sda.
        SelectCommand.Connection = conn;
         Sda.SelectCommand.CommandText = SQL;
  Sda.SelectCommand.CommandType = CommandType.Text; Sda. SelectCommand.Parameters.AddWithValue ("@ProvinceID", id);//Parameter settings don't forget to//3. Open Connection "Note that, in the non-link mode, the connection is turned off, it doesn't matter, but it's better to turn it on." Normalize "conn".

  Open (); 4. Send command SDA.

  Fill (DS); 5. Processing data//6 Close connection "" Note that in the non-link mode, the connection is turned off, it doesn't matter, but it's better to turn it on. Normalize "" Conn.

  Close (); return datatabletolist<city>. Converttomodel (ds. Tables[0]).
 Tolist<city> (); 

 }
 }
}

DataTable to list, I found a help class on the Internet:

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)
 {
  //definition set
  ilist<t> ts = new List<t > ();
  T t = new t ();
  String tempname = "";
  Gets the public properties of this model
  propertyinfo[] Propertys = T.gettype (). GetProperties ();
  foreach (DataRow row in dt. Rows)
  {
  t = new T ();
  foreach (PropertyInfo pi in propertys)
  {
   tempname = pi. Name;
   Check if the DataTable contains this column
   if (dt. Columns.contains (tempname))
   {
   //Determine if this property has set
   if (!PI). CanWrite)
    continue;
   Object value = Row[tempname];
   if (value!= dbnull.value)
    Pi. SetValue (t, value, NULL);
   }
  Ts. ADD (t);
  }
  return ts;
 }
 }
 

To create a province controller:

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

The corresponding index view:

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

 
 

Modify the default route,

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

First look at the next stage of the results: Run the program:

Look, this loads all the province data, and now we're going to go further and load the data into another drop-down box when we select a province.
Modify the controller to add a method:

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

In the index view:

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

All right, after it's done, run the program:
Select a province, the corresponding city information is we find out, bound to another city's Drop-down box.

Summary: This article, although the basis, but very important, peacetime development, encountered a lot of such scenes.
There is more EF use, ADO. NET also can't forget.
Connection mode and non-link mode query database 6 steps, keep in mind.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.