【问题标题】:How can I maintain the original value of the DropDownList variable?如何保持 DropDownList 变量的原始值?
【发布时间】:2012-07-24 02:59:24
【问题描述】:

我在控制器中使用Viewbag.typeofchange 将列表传递给视图。在创建网页/视图中,如果选择了 dropdownlist 项目,则它会正确保存到实体模型/数据库中。

但是,在编辑网页/视图中,下拉列表显示原始值,但在保存页面时,如果未选择下拉列表中的新项目,则该值丢失。

在编辑视图中,如果选择dropdownlist,则新值将存储到数据库中。

如何保持dropdownlist变量typeofchange的原始值,以免用户不选择某项时丢失?

控制器中的代码:

    List<SelectListItem> items = new List<SelectListItem>();
    items.Add(new SelectListItem { Text = "Red", Value = "Red" });
    items.Add(new SelectListItem { Text = "Green", Value = "Green" });
    items.Add(new SelectListItem { Text = "Blue", Value = "Blue" });
    items.Add(new SelectListItem { Text = "Other/Explain", Value = "Other" });
    ViewBag.typeofchange = items;

编辑视图中的代码:

    <div class="editor-field">
        @Html.DropDownList("typeofchange", Model.typeofchange)
    </div>

Entity CodeFirst 模型中的代码:

    [DisplayName("Type of Change")]
    public string typeofchange { get; set; }

非常感谢您的反馈。

【问题讨论】:

  • 从控制器中,您将其设置在 ViewBag 上。在视图中,您从模型中使用它。哪个错了?
  • 感谢您的回复,我将开始研究这个。基本上,我使用 Model.typeofchange 值来显示模型中的当前值,我想我将不得不从模型变量的控制器中的 Viewbag 中设置默认值。
  • 您需要一个列表来创建下拉列表,并且需要模型来设置所选值。两者都有,只需在视图上正确使用它们即可。
  • 感谢安德烈,在控制器中添加 selected = true 解决了问题。即: items.Add(new SelectListItem { Text = model.typeofchange, Value = model.typeofchange, Selected = true });再次感谢。
  • 把它扔到 Andre 下面的答案中,这样你就可以获得答案的分数(用户可以将其标记为已接受)

标签: c# asp.net-mvc-3 entity-framework html-select


【解决方案1】:

您有两个变量,typeofchange 是在 ViewBag 中传递的 SelectList,typeofchange 是模型的一部分。您需要做的就是将模型 typeofchange 设置为选定的值,然后将为您设置相关 SelectListItem 的 Selected 属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    相关资源
    最近更新 更多