美好的一天,为什么当我选择父下拉列表时我的第二个 DDL 没有触发。任何人都可以在m=>m.StateModel旁边的视图中详细说明脚本和[ 0]
对于最后一个问题,如何使这个 DDL 动态化,如何使用数据库数据填充它?
模型
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Kaskid.Models
{
public class State
{
public int Id { get; set; }
public string StateName { get; set; }
}
public class City
{
public int Id { get; set; }
public int StateId { get; set; }
public string CityName { get; set; }
}
public class CountryModel
{
public List<State> StateModel { get; set; }
public SelectList FilteredCity { get; set; }
}
}
控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kaskid.Models;
namespace Kaskid.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
CountryModel objCountryModel = new CountryModel();
objCountryModel.StateModel = new List<State>();
objCountryModel.StateModel = GetAllState();
return View(objCountryModel);
}
[HttpPost]
public ActionResult GetCityByStateId(int stateId)
{
List<City> objCity = new List<City>();
objCity = GetAllcity().Where(m => m.StateId == stateId).ToList();
SelectList obgcity = new SelectList(objCity, "Id", "CityName", 0);
return Json(obgcity);
}
public List<State> GetAllState()
{
List<State> objState = new List<State>();
objState.Add(new State {Id = 0,StateName="Select State"});
objState.Add(new State {Id = 1,StateName = "State 1"});
objState.Add(new State {Id = 2, StateName="State 2"});
objState.Add(new State {Id = 3, StateName="State 3"});
return objState;
}
public List<City> GetAllcity()
{
List<City> objCity = new List<City>();
objCity.Add(new City{Id = 1,StateId = 1, CityName = "City1-1" });
objCity.Add(new City{Id = 2,StateId=2,CityName = "City2-1"});
objCity.Add(new City{Id = 3,StateId=4,CityName="City4-1"});
objCity.Add(new City{Id = 4,StateId=1,CityName="City1-2"});
return objCity;
}
}
}
看法
@model Kaskid.Models.CountryModel
@{
ViewBag.Title = "Index";
}
<script language="javascript">
function GetCity(_stateId) {
var procemessage = "<option value='0'> Please wait...</option>";
$('#ddlcity').html(procemessage).show();
var url = "/Home/GetCityByStaeId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$('#ddlcity').html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
</script>
<h4>
MVC3 Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm("", ""))
{
@Html.DropDownListFor(m => m.StateModel[0].Id, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
<br />
<br />
<select id="ddlcity" name="ddlcity" style="width: 200px">
</select>
}