【问题标题】:Save dropdownlist state after form submit in mvc在 mvc 中提交表单后保存下拉列表状态
【发布时间】:2013-08-04 20:02:39
【问题描述】:

我有一个表单和 Html.DropDownList。表单提交后,下拉列表状态更改为默认值。表单提交后如何保持下拉列表状态?

@using (Html.BeginForm("Result", "Controller", FormMethod.Post, new { id = "Form" }))
           {
             @Html.DropDownListFor(x => x.DropList, new[] { 
                new SelectListItem() {Text = "first", Value = "first"}, 
                new SelectListItem() {Text = "second", Value = "second"},
                new SelectListItem() {Text = "third", Value = "third"} 
                }, "DefaultState")

提前致谢。

【问题讨论】:

  • 你能展示负责表单后期处理的控制器部分吗?

标签: asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

你不能。除非在提交后,您将模型传回视图。你为什么要这样做?因为在提交表单后,表单应该重置并准备好进行另一个数据输入会话,不是吗?

【讨论】:

  • 我知道这已经很晚了,但我在同一点 ATM 上挣扎。如果出现验证错误,我想保留信息选择。
【解决方案2】:

使用 SelectListItem 的 Selected 属性

另外,请确保 Model.DropList 的值已在帖子中设置在您的控制器中。

  @using (Html.BeginForm("List", "Home", FormMethod.Post, new { id = "Form" }))
       {
         @Html.DropDownListFor(x => x.DropList, new[] { 
            new SelectListItem() {Text = "first", Value = "first", Selected = Model.DropList == "first"}, 
            new SelectListItem() {Text = "second", Value = "second", Selected = Model.DropList == "second"},
            new SelectListItem() {Text = "third", Value = "third", Selected = Model.DropList == "third"} 
            }, "DefaultState")

【讨论】:

  • 这取决于你是否是模型绑定。如果您将模型作为操作方法的参数传递(并假设它正确绑定),那么您需要确保将模型传递给视图。否则,您将需要获取 DropList 的值并在模型上设置 DropList 属性(再次将模型传递给视图)
  • 按照@Andrei 的建议发布您的控制器操作方法可能是值得的
  • DropList 是 LinksListViewModel 的属性吗?如果是这样,那么您需要在 Type = DropList 之后添加行 DropList = DropList
猜你喜欢
  • 2013-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-18
相关资源
最近更新 更多