我必须建立一个带有2个动态下拉列表字段的Razor注册表单。第一个是Country字段,第二个是Region字段,第一个更改时必须填充该字段。国家/地区列表和相关区域列表存储在我的Sql Db中。我的Razor View看起来像这样:
@model Web.Models.ProfileModel
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
@Html.ValidationSummary(true)
@using (Html.BeginForm("Register", "Profile", FormMethod.Post, new { id = "RegForm" }))
{
...
<div class="editor-field">
@Html.DropDownListFor(x => x.selectedCountry, new SelectList(Model.companyCountry, "Value", "Text"), "Please select a country", new { id = "ddlCountry" })
@Html.ValidationMessageFor(x => x.selectedCountry)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.companyRegion)
</div>
<div class="editor-field">
@Html.DropDownListFor(x => x.selectedRegion, new SelectList(Model.companyRegion, "Value", "Text"), "Please select a region", new { id = "ddlRegion" })
@Html.ValidationMessageFor(x => x.selectedRegion)
</div>
...
}
在我的视图底部我有这些脚本。第一个是:
$("#ddlCountry").change(function () {
$("#Loading").empty().html('<img src="../../Content/ajax-loader.gif" />');
var list = $("#ddlRegion")[0];
list.options.length = 0;
var option = new Option("Loading....", 0);
list.add(option);
var strSelected = "";
$("#ddlCountry option:selected").each(function () {
strSelected += $(this)[0].value;
});
$.getJSON("UpdateDdlRegion", { id: strSelected },
function (response) {
loadDdlRegion(response)
}
);
$("#Loading").empty();
});
第二个在这里:
function loadDdlRegion(response) {
var list = $("#ddlRegion")[0];
list.options.length = 0;
var option = new Option("@Core.Resources.Resources.ddlregion_msg", "");
list.add(option);
for (var i = 0; i < response.length; i++) {
var region = response[i];
var option = new Option(region.RegionName,region.Id);
list.add(option);
}
}
它似乎在IE9和Chrome中正常运行,但在Firefox 5/6中没有! 任何的想法?我不知道这是否是实现这些下拉列表的正确方法。如果您以其他方式思考,请回复!