create table TypeInfo
(
TypeId int Primary key,
TypeName varchar(20)
)
create table ItemInfo
(
ItemId int primary key,
TypeId int foreign key references TypeInfo(TypeId),
ItemName varchar(20)
)
insert into TypeInfo values(1,'动物')
insert into TypeInfo values(2,'植物')
isnert into ItemInfo values(1,1,'老虎')
isnert into ItemInfo values(2,1,'老鼠')
isnert into ItemInfo values(3,2,'花')
isnert into ItemInfo values(4,2,'草')
View代码:
@using System.Data
@{
DataTable TypeData = (DataTable)ViewBag.TypeData
}
<!DOCTYPE html>
<html>
<head>
<title>Main</title>
<script src="@Url.Content("~/Scripts/jquery.min.js")" type="text/javascript"></script>
<script>
$(function () {
$("#select1").change(function () {
var typeid = this.value
$.ajax({
url: "@Url.Action("GetItems")",
type: "Post",
data: { "typeid": typeid },
dataType: "json",
success: function (data) {
$("#select2").empty()
for (var i = 0 i < data.length i++) {
$("#select2").append("<option value='" + data[i].ItemId + "'>" + data[i].ItemName + "</option>")
}
}
})
})
})
</script>
</head>
<body>
<div style="padding:5px 5px 0px 5px">
<select id="select1" name="select1">
<option value="0">--select--</option>
@foreach(DataRow row in TypeData.Rows){
<option value="@row["TypeId"]">@row["TypeName"]</option>
}
</select>
<select id="select2" name="select2"><option value="0">--select--</option></select>
</div>
</body>
</html>
Controller代码:
using System
using System.Collections.Generic
using System.Linq
using System.Web
using System.Web.Mvc
using System.Data
using App.Common
namespace My.Web.Controllers
{
public class TestController : Controller
{
//
// GET: /Test/
public ActionResult Index()
{
DataTable type_table = SQLHelper.GetDataTable("select TypeId,TypeName from TypeInfo")
ViewBag.TypeData = type_table
return View()
}
[HttpPost]
public string GetItems(string typeid)
{
DataTable type_table = SQLHelper.GetDataTable("select ItemId,ItemName from ItemInfo where TypeId=" + typeid)
string json = ""
foreach (DataRow row in type_table.Rows)
{
if (json == "")
{
json += "{\"ItemId\":\"" + row["ItemId"] + "\",\"ItemName\":\"" + row["ItemName"] + "\"}"
}
else
{
json += ",{\"ItemId\":\"" + row["ItemId"] + "\",\"ItemName\":\"" + row["ItemName"] + "\"}"
}
}
string jsonvalue = "[" + json + "]"
return jsonvalue
}
}
}
你这个是没有错误的,我拿到本地执行也成功,你检查下页面上是不是没有id=selectID的下拉框,或者是存在同名的id了
<select id="selectID"></select>
$("#selectID").append("<option value='7'>7</option>")
结果:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)