1. AjaxBindDropdownlistController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcAppEntities;
namespace MvcAppDemoCly.Controllers
{
public class AjaxBindDropdownlistController : Controller
{
public ActionResult LoadProvince()
{
var provinces = Province.GetProvinces();
return Json(new SelectList(provinces, "Id", "Name"), JsonRequestBehavior.AllowGet);
}
public ActionResult LoadCity()
{
//string testuservalue = Request.Params["nouservar"];
int provinceId = -1;
Int32.TryParse(Request.Params["provinceid"], out provinceId);
var cities = City.GetCitiesByProvinceId(provinceId);
//return Json(new SelectList(cities,"Id","Name"), JsonRequestBehavior.AllowGet);
return Json(cities, JsonRequestBehavior.AllowGet);
}
//
// GET: /AjaxBindDropdownlist/
public ActionResult Index()
{
return View();
}
//
// GET: /AjaxBindDropdownlist/Details/5
public ActionResult Details(int id)
{
return View();
}
//
// GET: /AjaxBindDropdownlist/Create
public ActionResult CreateProvince()
{
return View();
}
//
// POST: /AjaxBindDropdownlist/Create
[HttpPost]
public ActionResult CreateProvince(Province p)
{
try
{
if (!this.ModelState.IsValid)
{
return View();
}
if (p != null)
{
// TODO: Add insert logic here
Province.InsertProvince(p);
return RedirectToAction("Index");
}
ViewData["CreateResult"] = "Created Failed!";
return View();
}
catch
{
ViewData["CreateResult"] = "Created Failed!";
return View();
}
}
//
// GET: /AjaxBindDropdownlist/Create
public ActionResult CreateCity()
{
var provinceList = Province.GetProvinces();
ViewData["Provinces"] = new SelectList(provinceList, "Id", "Name");
return View();
}
//
// POST: /AjaxBindDropdownlist/Create
[HttpPost]
public ActionResult CreateCity(City c)
{
var provinceList = Province.GetProvinces();
ViewData["Provinces"] = new SelectList(provinceList, "Id", "Name");
try
{
if (!this.ModelState.IsValid)
{
return View();
}
if (c != null)
{
// TODO: Add insert logic here
City.InsertCity(c);
return RedirectToAction("Index");
}
ViewData["CreateResult"] = "Created Failed!";
return View();
}
catch
{
ViewData["CreateResult"] = "Created Failed!";
return View();
}
}
//
// GET: /AjaxBindDropdownlist/Edit/5
public ActionResult Edit(int id)
{
return View();
}
//
// POST: /AjaxBindDropdownlist/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /AjaxBindDropdownlist/Delete/5
public ActionResult Delete(int id)
{
return View();
}
//
// POST: /AjaxBindDropdownlist/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
2. Index.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Index
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script src="../../Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
function json2string(strObject) {
var c, i, l, s = '', v, p;
switch (typeof strObject) {
case 'object':
if (strObject) {
if (strObject.length && typeof strObject.length == 'number') {
for (i = 0; i < strObject.length; ++i) {
v = json2string(strObject[i]);
if (s) {
s += ',';
}
s += v;
}
return '[' + s + ']';
} else if (typeof strObject.toString != 'undefined') {
for (i in strObject) {
v = strObject[i];
if (typeof v != 'undefined' && typeof v != 'function') {
v = json2string(v);
if (s) {
s += ',';
}
s += json2string(i) + ':' + v;
}
}
return '{' + s + '}';
}
}
return 'null';
case 'number':
return isFinite(strObject) ? String(strObject) : 'null'; case 'string': l = strObject.length; s = '"';
for (i = 0; i < l; i += 1) {
c = strObject.charAt(i);
if (c >= ' ') {
if (c == '\\' || c == '"') {
s += '\\';
}
s += c;
} else {
switch (c) {
case '\b': s += '\\b'; break;
case '\f': s += '\\f'; break;
case '\n': s += '\\n'; break;
case '\r': s += '\\r'; break;
case '\t': s += '\\t'; break;
default: c = c.charCodeAt(); s += '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
}
}
}
return s + '"';
case 'boolean': return String(strObject);
default: return 'null';
}
}
$(document).ready(function () {
LoadProvince();
$("#city").append("<option value='-1'>" + "Please select…" + "</option>");
$("#province").change(function () {//chang事件
$("#city").empty();
var provinceid = $("#province").val();
LoadCity(provinceid);
});
});
function LoadProvince() {//load province
$.ajax({
type: "get",
dataType: "json",
url: "/AjaxBindDropdownlist/LoadProvince",
success: function (msg) {
var data = msg;
$("#province").append("<option value='-1'>" + "Please select…" + "</option>");
//alert(json2string(data));
//alert(data[0].Text);
for (var i = 0; i < data.length; i++) {
$("#province").append("<option value='" + data[i].Value + "'>" + data[i].Text + "</option>");
}
}
});
}
function LoadCity(provinceid) {//LoadCity
$.ajax({
type: "get",
dataType: "json",
url: "/AjaxBindDropdownlist/LoadCity",
data: { provinceid: provinceid, nouservar: "testvalue" },
success: function (msg) {
var data = msg;
//alert(json2string(data));
//alert(data[0].Name);
for (var i = 0; i < data.length; i++) {
$("#city").append("<option value='" + data[i].Id + "'>" + data[i].Name + "</option>");
}
}
});
}
</script>
<h2>
Index</h2>
<%: Html.ActionLink("Create Province","CreateProvince") %>
<%: Html.ActionLink("Create City","CreateCity") %>
<br />
<br />
<br />
<div id="SelectTest">
Province:<select id="province" name="D1">
</select><br />
City:
<select id="city" name="D2">
</select>
</div>
</asp:Content>
3. Models
a) ProvinceModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace MvcAppDemoCly.Models
{
public class Province
{
public int Id { get; set; }
[Required]
[DisplayName("Province Name")]
public string Name { get; set; }
[DisplayName("Description")]
public string Description { get; set; }
}
}
b) CityModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace MvcAppDemoCly.Models
{
public class City
{
public int Id { get; set; }
[Required]
[DisplayName("Province Name")]
public string Name { get; set; }
[DisplayName("Description")]
public string Description { get; set; }
public int ProvinceId { get; set; }
}
}