【问题标题】:DropDownListFor setting value of other property when using shared SelectListDropDownListFor 使用共享 SelectList 时设置其他属性的值
【发布时间】:2018-09-26 15:12:45
【问题描述】:

我的视图上有两个下拉菜单,它们共享模型中的相同 SelectList。我遇到的问题是,如果为“Primary”而不是“Secondary”选择了一个值,当加载带有所选数据的页面时,“Primary”和“Secondary”都将具有相同的选定值。如果选择了两者的值,则将显示正确的值。我怎样才能让它不显示两者的价值?

示例模型:

public class ExampleViewModel 
{
     public string Primary { get; set; }
     public string Secondary { get; set; }
     public IEnumerable<string> Categories { get; set; }
}

示例视图:

...
@model Categories
...
<div class="form-group">
     @Html.DropDownListFor(x => x.Primary, Model.Categories, "", new { @class = "form-control" })
</div>
<div class="form-group">
     @Html.DropDownListFor(x => x.Secondary, Model.Categories, "", new { @class = "form-control" })
</div>
...

示例控制器:

public ActionResult Index(string primary, string secondary)
{
     return View(new ExampleViewModel {
          Primary = primary,
          Secondary = secondary,
          Categories = context.Query<Categories>().Select(x => new SelectListItem {
               Text = x.Name
           }));
}

【问题讨论】:

  • 创建另一个与类别相同类型的模型属性,将其命名为不同的名称,将类别值复制到所述列表中,然后将其绑定到辅助下拉列表。
  • 这是一个选项,但如果可能的话,我宁愿在我的模型中不要有重复的属性
  • 在 html 帮助器中,尝试添加新的 SelectList(Model.Categories), ""。检查重载,因为我不记得确切的语法,但我认为您需要指定 "Text","Value"
  • @Wheels73 成功了。我做了新的 SelectList(Model.Categories, "Value", "Text")
  • @Talon - 太棒了。我可以发布答案吗?

标签: c# asp.net-mvc razor asp.net-mvc-5


【解决方案1】:

如前所述,添加新的 SelectList(Model.Categories),"Value","Text")。 根据评论检查重载的语法。

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 2016-09-21
    相关资源
    最近更新 更多