今天用一张表做下二级联动,现在有一张表Address
create table Address
(
Id int primary key identity,--主键
AName varchar(50),--地名
PId int
)
添加值
insert into Address values('上海',0)
insert into Address values('北京',0)
insert into Address values('奉贤',1)
insert into Address values('浦东',1)
insert into Address values('静安',1)
insert into Address values('朝阳',2)
insert into Address values('房山',2)
insert into Address values('海淀',2)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using 二级联动.EF;
using Newtonsoft.Json;
namespace 二级联动.Controllers
{
public class StudentController : Controller
{
A v = new A();
// GET: Student
public ActionResult GetShi()
{
Model1 n = new Model1();
List<Address> list =v.GetAresses(0) ;
var sel = from a in list
select new SelectListItem
{
Text = a.AName,
Value = a.AId.ToString()
};
ViewBag.a = sel;
//GetQu(1);
return View();
}
public ActionResult GetQu(int pid)
{
List<Address> list = v.GetAresses(pid);
var sel = from a in list
select new SelectListItem
{
Text = a.AName,
Value = a.AId.ToString()
};
return Json(sel);
}
}
class A
{
public List<Address> GetAresses(int pid)
{
Model1 m = new Model1();
return m.Address.Where(s => s.PId == pid).ToList();
}
}
}
视图页面
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<meta name="viewport" content="width=device-width" />
<title>GetShi</title>
</head>
<body>
<div>
<table>
<tr>
<th>
市:
</th>
<th>
@Html.DropDownList("sid", ViewBag.a as IEnumerable<SelectListItem>)
</th>
</tr>
<tr>
<th>
区:
</th>
<th>
<select id="qid"></select>
</th>
</tr>
</table>
</div>
</body>
</html>
<script>
$("#sid").change(function () {
$.ajax({
url: '/Student/GetQu',
type: 'post',
data: { 'pid': $("#sid").val() },
success: function (data) {
$("#qid").empty();
alert(312);
$(data).each(function () {
var option = " <option value=" + this.Value + ">" + this.Text + "</option>";
$('#qid').append(option);
})
}
})
})
</script>