【问题标题】:Html.DropDownListFor() Changes the SelectListItems in ASP.NET MVCHtml.DropDownListFor() 更改 ASP.NET MVC 中的 SelectListItems
【发布时间】:2016-04-08 21:45:20
【问题描述】:

我需要一个 DropDownList 在页面中,所以我尝试这种方式:

行动:

[HttpGet]
public ActionResult GetPoint() {

  ...
  List<SelectListItem> zooms = new List<SelectListItem>();
    for (int i = 0; i <= 21; i++) {
      if (i == 9)
        zooms.Add(new SelectListItem() { Selected = true, Text = i.ToString(), Value = i.ToString() });
      else
        zooms.Add(new SelectListItem() { Selected = false, Text = i.ToString(), Value = i.ToString() });
            }
  model.myselectlist = zooms;
  ...

  return View(model);
}

在视图中:

@Html.DropDownListFor(model => model.Zoom, Model.myselectlist , new { @class = "dropdown" })

正如我所料,我们有一个 DropDownList,其中 9 是选定项。

但是在同一个视图中我需要另一个 DropDown 所以这是我的实现:

[HttpGet]
public ActionResult GetPoint() {

  ...

  List<SelectListItem> places = new List<SelectListItem>();
  places.Add(new SelectListItem() { Text = "NY", Value = "NY", Selected = false });
  places.Add(new SelectListItem() { Text = "CA", Value = "CA", Selected = false });
  places.Add(new SelectListItem() { Text = "TX", Value = "TX", Selected = false });
  places.Add(new SelectListItem() { Text = "NH", Value = "NH", Selected = true });
  places.Add(new SelectListItem() { Text = "NV", Value = "NV", Selected = false });
  model.myselectlistII = places;

  ...

  return View(model);
}

在视图中我有:

@Html.DropDownListFor(model => model.Place, Model.myselectlistII , new { @class = "dropdown" })

如您所见,我有一个列表,NH 项目具有selected = true

我希望NH 选择了一个下拉列表,但没有发生,并且始终是第一个选择的项目。

鉴于我有一个奇怪的行为,我在 Action 末尾和视图页面中 @Html.DropDownListFor 行的开头调试代码,一切正常,但在此行之后我再次检查 Model.myselectlistII已选择的项目已更改,并且所有项目都具有 false 的 Selected 属性,我不明白发生了什么?问题出在哪里?为什么第一个DropDownFor 没有改变任何东西,但第二个改变了我的列表?你有什么建议?

【问题讨论】:

  • 您是否为模型字段Place 设置了任何值(例如,在构造函数中或其他地方)?如果是这种情况,它将覆盖您列表的 Selected 字段...
  • @SamuelCaillerie 你说得对,其实我没有设置任何东西,我必须设置默认值。
  • @SamuelCaillerie 所以请发表你的答案,以供下次参考
  • 这不是一个真正的答案,只是一个猜测,因为我不知道你的 ActionResult GetPoint() 和你的模型 model 中有什么,但你的 @Html.DropDownListFor() 是基于该字段的model.Place,如果这个字段被初始化了,这将覆盖你在model.myselectlistII中的Selected值...

标签: asp.net-mvc html.dropdownlistfor


【解决方案1】:

Samuel Caillerie 是正确的。您正在使用 DropDownListFor 将您的属性 Zoom 和 Place 绑定到选择列表。无论这些属性的值是什么,都将在视图呈现时选择。还没有找到很好的文档,但是这里有另一个堆栈溢出帖子来帮助支持它:

asp.net mvc 3 pre-select Html.DropDownListFor not working in nerd dinner

【讨论】:

    【解决方案2】:

    如果有 QUERY STRING 同名,请注意,它会覆盖该行为,不确定 HIDDEN FIELDS 是否与 同名

    DropDownListFor 将使用 DinnerID 的 Query String 的值,如果 成立 块引用

    【讨论】:

      【解决方案3】:

      我在我的一个项目中所做的并且有点用处的是,为
      DropDownListFor 开发了另外 2 个重载,它们接受 selectedValue

      namespace MyMvcApplication.Helpers
      {
          public static class ExtensionMethods
          {
              public static MvcHtmlString DropDownListFor<TModel, TProperty>
                                   (this HtmlHelper<TModel> helper,
                                    Expression<Func<TModel, TProperty>> expression,
                                    string selectedValue,
                                    IEnumerable<SelectListItem> selectList,
                                    string optionLabel,
                                    object htmlAttributes)
              {
                  if (string.IsNullOrEmpty(selectedValue))
                      selectedValue = string.Empty;
                  if (selectList != null)
                  {
                      foreach (SelectListItem sli in selectList)
                      {
                          if (sli.Value.ToLower().Trim() == selectedValue.ToLower().Trim())
                          {
                              sli.Selected = true;
                              break;
                          }
                      }
                  }
                  else 
                  { 
                      selectList = new List<SelectListItem>() 
                                        { new SelectListItem() 
                                                { Text = "", Value = "", Selected = true }
                                        };
                  }
                  return helper.DropDownListFor(expression, selectList, optionLabel, htmlAttributes);
              }
      
      
              public static MvcHtmlString DropDownListFor<TModel, TProperty>
                                   (this HtmlHelper<TModel> helper,
                                    Expression<Func<TModel, TProperty>> expression,
                                    string selectedValue,
                                    IEnumerable<SelectListItem> selectList,
                                    string optionLabel,
                                    IDictionary<string, object> htmlAttributes)
              {
                  if (string.IsNullOrEmpty(selectedValue))
                      selectedValue = string.Empty;
                  if (selectList != null)
                  {
                      foreach (SelectListItem sli in selectList)
                      {
                          if (sli.Value.ToLower().Trim() == selectedValue.ToLower().Trim())
                          {
                              sli.Selected = true;
                              break;
                          }
                      }
                  }
                  else 
                  { 
                      selectList = new List<SelectListItem>() 
                                        { new SelectListItem() 
                                                { Text = "", Value = "", Selected = true } 
                                        };
                  }
                  return helper.DropDownListFor(expression, selectList, optionLabel, htmlAttributes);
              }
      
          }
      }
      

      所以在视图中,我可以将一个字符串作为 selectedValue 传递给DropDownListFor,例如:

      @using MyMvcApplication.Helpers
      
      @Html.DropDownListFor(model => model.MyData,
                                     "Default Value for DropDownList", //Or Model.MySelectedValue
                                     Model.MySelectList, null, null)
      

      【讨论】:

        【解决方案4】:

        这个问题的解决方案比我们都认为的更简单......

        当从控制器返回视图时,我们需要做的就是在视图模型上为下拉绑定到的元素设置属性 - 例如:model.Zoom = 'NH'

        当我们这样做时就这样

        @Html.DropDownListFor(model => model.Zoom, Model.myselectlist , new { @class = "dropdown" })
        

        HtmlHelper 会自动选取默认值显示在 DropDownList 上

        简单!

        希望它可以帮助您和所有其他人 - 像我一样! - 已经浪费了很多时间来寻找这个明显问题的解决方案。

        【讨论】:

          【解决方案5】:

          大家看看!!!超级静态功能懒惰的方式来选择/选择/绑定下拉列表用于 mvc razor 引导样式;)作为奖励去插入法语或英语描述!你的改进,但你会很容易得到这个想法。 玩得开心! MightyMart ...

                        <div class="form-group">
                              <label>@(HttpContext.Current.Session["culture"].ToString().Equals("fr-CA") ? "Quel est votre niveau d'expertise" : "What is your skill level")</label>
                              @if (Model.ClientLevel == null)
                              {
                                  <select class="form-control" name="ClientLevel">
                                      <option selected value="0">@(HttpContext.Current.Session["culture"].ToString().Equals("fr-CA") ? "Choisir un niveau" : "Choose a level")</option>
                                      <option value="1">@(HttpContext.Current.Session["culture"].ToString().Equals("fr-CA") ? "Débutant" : "Beginner")</option>
                                      <option value="2">@(HttpContext.Current.Session["culture"].ToString().Equals("fr-CA") ? "Intermédiaire" : "Intermediate")</option>
                                      <option value="3">@(HttpContext.Current.Session["culture"].ToString().Equals("fr-CA") ? "Advanced" : "Advanced")</option>
                                      <option value="4">@(HttpContext.Current.Session["culture"].ToString().Equals("fr-CA") ? "Expert" : "Expert")</option>
                                      <option value="5">@(HttpContext.Current.Session["culture"].ToString().Equals("fr-CA") ? "Autre" : "Other")</option>
                                  </select>
                              }
                              else
                              {
          
                                  List<SelectListItem> listItems = new List<SelectListItem>();
                                  listItems.Add(new SelectListItem() { Text = "Choose a level", Value = "Choose a level"});
                                  listItems.Add(new SelectListItem() { Text = "Beginner", Value = "Beginner" });
                                  listItems.Add(new SelectListItem() { Text = "Intermediate", Value = "Intermediate"});
                                  listItems.Add(new SelectListItem() { Text = "Advanced", Value = "Advanced"});
                                  listItems.Add(new SelectListItem() { Text = "Expert", Value = "Expert"});
                                  listItems.Add(new SelectListItem() { Text = HttpContext.Current.Session["culture"].ToString().Equals("fr-CA") ? "Autre" : "Other", Value = "Other"});
          
                                  @Html.DropDownListFor(m => m.ClientLevel, listItems, new { @class = "form-control" })
                              }
                          </div>
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-02-20
            • 1970-01-01
            • 2014-11-21
            • 2011-01-19
            • 2011-03-04
            相关资源
            最近更新 更多