我正在为我们的MVC应用创建一个编辑页面,其中包含国家和州的下拉菜单。我有下降填充。国家/地区在页面加载时加载,当选择国家/地区时,将加载状态列表。编辑时,填写并正确选择国家/地区列表。
我的问题是如何设置要选择的状态。这是我到目前为止所做的:
<div class="form-group col-md-4">
@Html.LabelForRequired(model => model.CountryId, htmlAttributes: new {@class = "control-label"})
@Html.DropDownListFor(model => model.CountryId,
new SelectList(ViewBag.Countries as IEnumerable, "CountryId", "CountryName"),
new {@class = "form-control", id = "ddlCountry"})
@Html.ValidationMessageFor(model => model.CountryId, "", new {@class = "text-danger"})
</div>
<div class="form-group col-md-4">
@Html.LabelForRequired(model => model.State, new {@class = "control-label"})
<select id="ddlState" name="@Html.NameFor(model => model.State)"></select>
@Html.ValidationMessageFor(model => model.State, "", new {@class = "text-danger"})
</div>
这是我的剧本:
<script>
$(function () {
LoadStates();
$("#ddlCountry").change(function () {
LoadStates();
});
});
function LoadStates() {
var Param = { CountryId: $("#ddlCountry > option:selected").attr("value") };
$.getJSON(appFolder + "Home/StateList/", Param, function (data) {
var items = "<option>Select State</option>";
$.each(data, function (i, state) {
items += "<option value=" + state.StateCode + ">" + state.State + "</option>";
});
$("#ddlState").html(items);
});
}
</script>
我一直在寻找一个例子,但还没找到一个。
答案 0 :(得分:1)
虽然您可以修改成功回调中的代码以包含$("#ddlState").val(someValue);
someValue
可能是模型或ViewBag
属性,但您当前的实现(手动创建<select>
element表示您没有获得强类型绑定,也没有得到客户端验证。
相反,在控制器中生成SelectList
(在SelectList
视图的情况下可能为空Create
)并将其传递给模型。请注意,它总是更适合使用视图模型,但可以修改以下内容以使用SelectLists的ViewBag
属性
查看模型
public class ViewModel
{
[Display(Name = "Country")]
[Required(ErrorMessage = "Please select a country")]
public int? CountryID { get; set; }
[Display(Name = "State")]
[Required(ErrorMessage = "Please select a state")]
public int? StateID { get; set; }
.... // other properties needed for the view
public IEnumerable<SelectListItem> CountryList { get; set; }
public IEnumerable<SelectListItem> StateList { get; set; }
}
控制器
private void ConfigureViewModel(ViewModel model)
{
var countries = db.Countries;
model.CountryList = new SelectList(countries, "CountryId", "CountryName");
if (model.StateID.HasValue)
{
var states = db.States.Where(s => s.CountryId == model.StateID.Value);
model.StateList = new SelectList(states, "StateId", "StateName");
}
else
{
model.StateList = new SelectList(Enumerable.Empty<SelectListItem>());
}
}
public ActionResult Create()
{
ViewModel model = new ViewModel();
ConfigureViewModel(model);
return View(model);
}
[HttpPost]
public ActionResult Create(ViewModel model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model);
return View(model);
}
// Initialize data model and set its properties based on view model
// Save data model and redirect
}
public ActionResult Edit(int ID)
{
// Get data model based on ID
ViewModel model = new ViewModel();
// Set properties based on data model
ConfigureViewModel(model);
return View(model);
}
[HttpPost]
public ActionResult Edit(ViewModel model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model);
return View(model);
}
// Get data model and set its properties based on view model
// Save data model and redirect
}
并在视图中
@Html.DropDownListFor(m => m.CountryID, Model.CountryList, new {@class = "form-control"})
....
@Html.DropDownListFor(m => m.StateID, Model.StateList, new {@class = "form-control"})
var url = '@Url.Action("StateList", "Home")'; // don't hard code your url's
var states = $('StateID'); // cache it
$('#CountryID').change(function() {
states.empty();
$.getJSON(url, { CountryId: $(this).val() }, function(data) { // use $(this)
if (!data) {
return;
}
// add empty option with value="" so you get client side validation
states.append($('<option></option>').val('').text('Please select'));
$.each(data, function(index, item) {
subLocalities.append($('<option></option>').val(item.StateCode ).text(item.State));
});
});