主要是查询
联表查询:
这是要查询的表,要把所有的信息显示在网页中,但是province和city要通过id从另外两张表获得
省份的表
省份和城市的表
我们需要在网页显示是这样的
所以就需要联表查询,通过省份和城市的id分别在两个表查到名字再显示出来
我们先在paper的model里加两个扩展字段
分别表示省份和城市的名字,然后在DAL层,做查找的方法,当然是写在省份和城市的表对应的DAL层(sql语句,使用 模糊查询)
public string GetNameByID(string proviceID)
{
StringBuilder strSql = new StringBuilder();
strSql.AppendLine("select * from Province");
strSql.AppendLine("where ProvinceID like '" + proviceID + "%'");
string name = "";
DataSet ds = DbHelperSQL.Query(strSql.ToString());
if(ds.Tables.Count>0&&ds.Tables[0].Rows.Count>0){
name = ConvertHelper.GetString(ds.Tables[0].Rows[0]["Name"]);
}
return name;
}
public string GetCityName(string cityid)
{
StringBuilder strSql = new StringBuilder();
strSql.AppendLine("select * from Province_City");
strSql.AppendLine("where CityID like '" + cityid + "%'");
string name = "";
DataSet ds = DbHelperSQL.Query(strSql.ToString());
if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
name= ConvertHelper.GetString(ds.Tables[0].Rows[0]["Name"]);
}
return name;
}
在BLL层调用一下,就可以使用了
public string GetnNameByID(string proviceID)
{
return dal.GetNameByID(proviceID);
}
这个是view层,写界面时候的列表,列名使用刚才加的两个扩展字段,因为ID还要使用,我们获得它,但是 把他隐藏了
然后是,条件查询,这张表我们查询的两个条件使用下拉框的方式选择,具体实现方法如下:
比较简单的是年份,写一个循环,把20个年份的数字存在list里面,然后在view界面的下拉框里调用这个list
List<int > listyear = new List<int>();
for (int i = 1; i <= 20; i++)
{
listyear.Insert(i - 1, 2020 - i);
}
ViewBag.listyear = listyear;
下拉框:
<select id="Year" name="Year" class="form-control">
<option value="" selected="selected">请选择年份</option>
@foreach (int item in ViewBag.listyear as List<int>)
{
<option value="@item">@item</option>
}
</select>
省份多一个步骤,先得到所有省份列表,再得到ID和Name的键值对列表,然后再放在下拉框里
DAL层
public List<KeyValuePair<string, string>> GetProvinceList()
{
List<KeyValuePair<string, string>> lst = new List<KeyValuePair<string, string>>();
DataSet ds = GetList("");
DataTable dt = ds.Tables[0];
foreach (DataRow item in dt.Rows)
{
string strKey = ConvertHelper.GetString(item["ProvinceID"]);
string strValue = ConvertHelper.GetString(item["Name"]);
KeyValuePair<string, string> pair = new KeyValuePair<string, string>(strKey, strValue);
lst.Add(pair);
}
return lst;
}
控制层
List<KeyValuePair<string, string>> lstProvince = new ProvinceBLL().GetProvinceList();
ViewBag.ProvinceList = lstProvince;
View层
<select id="ProvinceID" name="ProvinceID" class="form-control">
<option value="" selected="selected">请选择省份</option>
@foreach (KeyValuePair<string, string> item in ViewBag.ProvinceList as List<KeyValuePair<string, string>>)
{
<option value="@item.Key">@item.Value</option>
}
</select>
编辑页面仍然使用下拉框选择,因为直接可以修改省份的ID
<div class="form-group">
<label>
省份
</label><span class="required">*</span>
<select id="ProvinceID" name="ProvinceID" class="form-control">
<option value="" selected="selected"> @Model.Ext_ProviceName</option>
@foreach (KeyValuePair<string, string> item in ViewBag.ProvinceList as List<KeyValuePair<string, string>>)
{
<option value="@item.Key">@item.Value</option>
}
</select>
</div>