【发布时间】:2016-01-02 04:42:24
【问题描述】:
我在一个视图中有三个下拉菜单(级联)。第一个下拉元素来自 ViewModel。当第一个下拉列表更改时,我正在填充第二个下拉元素。和第三个下拉菜单一样。您可以在任何地方找到经典的级联下拉列表示例(例如:http://www.c-sharpcorner.com/UploadFile/4d9083/creating-simple-cascading-dropdownlist-in-mvc-4-using-razor/)
用户提交表单时出现问题。如果 ModelState 无效,则第 2 和第 3 个下拉菜单会丢失其项目,第 1 个下拉菜单会保留其状态。我理解他们为什么会这样,但不知道如何用用户选择的值再次填充它们。
场景
- 用户请求
/Country/Index - 在
page loaded之后,用户选择CountryId DropDownList- 将
Country Id发送到方法,如果结果不为空,则加载StateId DropDownList。
- 将
- 请勿填写
PostalCode Textbox并提交表单。 - 检查
CountryId DropDownlist是否已填充并选中,但StateId ropdownlist为空。 - 哭泣
查看
//HTML Code
//...
@Html.DropDownListFor(m => m.CountryId, ViewBag.Country as IEnumerable<SelectListItem>, "Select Country")
@Html.DropDownListFor(m => m.StateId, new SelectList(string.Empty, "Value", "Text"), "Select State")
@Html.DropDownListFor(m => m.CityId, new SelectList(string.Empty, "Value", "Text"), "Select City")
@Html.TextBoxFor(m=> m.PostalCode)
<script type="text/javascript">
var countryDDL = $("#CountryId");
countryDDL.change(function () {
$.ajax({
type: 'POST',
url: '@Url.Action("LoadStateList")',
dataType: 'json',
data: { countryId: countryDDL.val() },
success: function myfunction(states) {
$("#StateId").empty();
$.each(states, function (i, state) {
$("#StateId").append('<option value="' + state.Value + '">' + state.Text + '</option>');
}); }
});
return false;
});
//Code for 2nd (state) dropdownlist.change() method.
//...
</script>
控制器
public ActionResult Index()
{
ViewBag.CountryList = LoadCountryList();
return View();
}
[HttpPost]
public ActionResult Index(CountryViewModel cvm)
{
if(ModelState.IsValid)
{
//Save or do whatever you want
}
ViewBag.CountryList = LoadCountryList();
return View();
}
查看模型
public class CountryViewModel
{
public int CountryId {get;set;}
public int StateId {get;set;}
public int CityId {get;set;}
[Required]
public string PostalCode {get;set;}
}
【问题讨论】:
-
再次将模型传递回视图(在发布时处于无效状态),并在渲染
select时确保所选项目具有他们在将其提交到之前选择的 id服务器。 -
您的意思是再次在 HttpPost 方法中使用 CountryId 获取状态并发送回查看?如果是这样,这意味着我需要在 ViewBag.StateList 中发送具有初始值的 StateList 并更改 StateDDL 代码,例如使用 ViewBag.StateList 的 CountryDDL?合理。
-
我想你可能想多了(或者我错过了一些基本的东西)。难道你不需要将
cvm传递给View()吗? -
查看this DotNetFiddle中的代码——尤其是控制器代码。
标签: c# jquery model-view-controller drop-down-menu asp.net-mvc-5