有什么不对我DROPDOWNLIST [英] What is wrong with my Dropdownlist

查看:106
本文介绍了有什么不对我DROPDOWNLIST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下拉列表中不会选择我需要的值

The dropdown list will not select the value I need

 Dictionary<int,int> RowDict = new Dictionary<int, int>();
 for (int i = 1; i < 11; i++)
 {
      RowDict.Add(i, i);
 }
 var rows = new SelectList(RowDict, "Key", "Value", 6);
 ViewBag.Rows = rows;

下面是该视图中的code:

here is the code in the view:

  <div class="editor-label">
       @Html.LabelFor(m => m.Rows)
  </div>

 <div class="editor-field">
      @Html.DropDownListFor(m => m.Rows, (SelectList)ViewBag.Rows)
      @Html.ValidationMessageFor(m => m.Rows)
 </div>

当我运行code 6 没有被选中。你可以看到在这个code任何错误?第一个值被选中。

When I run the code 6 is not selected. Can you see any errors in this code? The first value is selected.

推荐答案

M => m.Rows表明有参与的典范。它的工作原理更好,如果你从模型做行初始化,而不是查看包里。

m => m.Rows suggests there is a model involved. It works better if you do the initialization with the rows from the model, not the view bag.

一个真正的快速和肮脏的初始化是这样的:

A really quick and dirty initialization like this :

   public class TestModel
   {
      public TestModel()
      {
         Dictionary<int, int> RowDict = new Dictionary<int, int>(); 
         for (int i = 1; i < 11; i++) 
         { 
            RowDict.Add(i, i); 
         }

         this.Rows = new SelectList(RowDict, "Key", "Value");
         this.SelectedId = "6"; // binding to selection works as a String
      }

      public SelectList Rows { get; set; }

      public string SelectedId { get; set; }

   }

这在要求视图控制器:

return View(new TestModel());

和开始像一个观点:

@model <insert_appropriate_anmespace_here>.TestModel

...

@Html.DropDownListFor(m => m.Rows, Model.Rows, Model.SelectedId) 

使得它的工作。你可以适应这个code和初始化你想要的方式,只要你还记得模型是按值传递给视图,为什么我安装我的初始化在构造函数(每次创建TestModel,选择列表中会得到初始化)。

makes it work. You can adapt this code and initialization the way you want, as long as you remember that models are passed by value to the view, reason why I setup my init in the constructor (every time a TestModel is created, the Select List will get initialized).

您也可以使viewbag和型号的混合,并有它的工作,我不会推荐它的可读性。

Also you can make a mix of viewbag and model and have it to work, I wouldnt recommend it for readability.

这篇关于有什么不对我DROPDOWNLIST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆