我在一个 View 中有三个下拉菜单(级联)。第一个下拉元素来自 ViewModel。当第一个下拉列表更改时,我正在填充第二个下拉元素。和第三个下拉菜单一样。您可以在任何地方找到的经典级联下拉列表示例(例如:http://www.c-sharpcorner.com/UploadFile/4d9083/creating-simple-cascading-dropdownlist-in-mvc-4-using-razor/)
用户提交表单时出现问题。如果 ModelState 无效,则第二个和第三个下拉列表将丢失其项目,而第一个下拉列表将保留其状态。我理解他们为什么会这样,但无法弄清楚如何用用户选择的值再次填充它们。
场景
- 用户请求
/Country/Index
页面加载
后,用户选择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>
Controller
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;}
}
最佳答案
实际的选择选项没有发布(也不应该发布)。因此,当您进行后期操作时,您的选择列表是空的。解决方案?只需像在 get 操作中一样重新填充它。当然,在这里,您不是在获取操作中填充这些内容,而是通过 AJAX 检索它们。如果你愿意,你可以在技术上以同样的方式在邮寄时做到这一点。您只需在页面加载时运行 AJAX 调用即可重新获取选择列表。然而,在这一点上,只在你的后行动中这样做会好得多。
关于c# - 如果表单具有无效的 ModelState,如何在 httppost 之后保留级联下拉列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32950066/