首先在View新增兩個下拉選單
@Html.DropDownList("select2",null ,new { id="Select2"})
@Html.DropDownList("select3",null ,new { id="Select3"})
根據上一篇的結果 我們會在Controll中把縣市的資料塞給Select2
Model ty = new Model();
public ActionResult Index()
{
ViewBag.select2 = ty.see();
ViewBag.select3 = ty.see3("3");
return View();
}
然後因為Select2有預設選項為3
所以我們在ty.see3(3)就給3
然後進Model開始寫see3()的方法如下
public List<SelectListItem> see3(string city)
{
string a = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(a);
conn.Open();
string sql = "select area , aid from area where id=@id";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@id", System.Data.SqlDbType.Int).Value = city;
SqlDataAdapter da = new SqlDataAdapter(sql,conn);
DataTable dt = new DataTable();
da.SelectCommand = cmd;
da.Fill(dt);
List<SelectListItem> yuii = new List<SelectListItem>();
for (int i = 0; i < dt.Rows.Count;i++ )
{
yuii.Add(new SelectListItem()
{
Text = dt.Rows[i].ItemArray[0].ToString(),
Value = dt.Rows[i].ItemArray[1].ToString()
});
}
da.Dispose();
dt.Dispose();
cmd.Dispose();
conn.Close();
conn.Dispose();
return yuii;
}
接著回到Controll另外寫個ActionResult:
public ActionResult details(string user)
{
var sop = ty.see3(user);
TagBuilder tb = new TagBuilder("select");
tb.GenerateId("Select3");
tb.MergeAttribute("name","select3");
foreach (var item in sop)
{
tb.InnerHtml+="<option value='"+item.Value.ToString()+"'>"+item.Text.ToString()+"</option>";
}
return Content(tb.ToString());
}
這邊是等AJAX呼叫時馬上去跟MODEL要資料再生成HTML程式碼return回去
記得ID要一樣,然後接著是前端的Jquery寫法如下
$("#Select2").change(function () {/*當縣市的下拉選單改變時*/
var selected = $("#Select2 option:selected");
$.post("@Url.Content("~/home/details")",
{ user: selected.val() },
function (res) {
$("#Select3").replaceWith(res);
});
});
如此一來,當縣市的選單改變後,會post選取值去Controll那邊
然後controll那邊會負責要資料在return出HTML,選區域的Select3的選項就會改變!
3月 24, 2014
MVC 高階連動式下拉選單DropDownList
訂閱:
張貼留言 (Atom)
1 則留言:
感恩您的分享,很棒的範例
張貼留言