【问题标题】:Trouble setting selected value of strongly typed MVC SelectList设置强类型 MVC SelectList 的选定值时遇到问题
【发布时间】:2015-05-18 19:04:02
【问题描述】:

从数据库中获取数据并添加我计划作为默认选择的选项:

    public List<Forester> GetForesters()
    {
        var data = _db.tblForester.ToList();

        List<Forester> ForesterList = new List<Forester>();

        foreach (var item in data)
        {
            Person person = new Person()
            {
                Key_ = item.Key_,
                FirstName = item.FirstName,
                LastName = item.LastName,
                District = item.District,
                County = item.County
            };
            PersonList.Add(person);
        }
        PersonList.Add(new Person { Key_ = -1, FirstName = "- Select ", LastName = "Person -" } );
        return PersonList;
    }

模型有两个属性:

    public int SelectedPersonId { get; set; }
    public IEnumerable<SelectListItem> PersonList { get; set; }

控制器从数据库中获取列表并制作一个选择列表:

        vm.SelectedPersonId = -1;
        vm.PersonList = new SelectList(repo.GetPeople(), "Key_", "PersonsName", vm.SelectedpersonId);

我在视图中尝试了几种方法:

                @Html.DropDownListFor(m => m.Key_, new SelectList( Model.PersonList, "Value", "Text", -1), new { @class = "form-control ddl" })

下拉菜单效果很好,除了所选值只是列表中的第一个,而不是我指定的那个。

以下是 HTML 的呈现方式:

<form action="/Forester/Activity" method="post"><select class="form-control ddl" data-val="true" data-val-number="The field Key_ must be a number." data-val-required="The Key_ field is required." id="Key_" name="Key_"><option value="1">DIANE PARTRIDGE</option>
<option value="2">GARY GROTH</option>

...

我添加的在底部:

<option value="-1">- Select   Forester -</option>

【问题讨论】:

    标签: asp.net asp.net-mvc razor html.dropdownlistfor selectlist


    【解决方案1】:

    如果你有以下型号

     public int SelectedPersonId { get; set; }
     public IEnumerable<SelectListItem> PersonList { get; set; }
    

    你应该使用

     @Html.DropDownListFor(m => m.SelectedPersonId , Model.PersonList, new { @class = "form-control ddl" })
    

    DropDownListFor helper 将评估 SelectedPersonId 并尝试选择它

    【讨论】:

    • 另外,您设置vm.PersonList 的行不应构造SelectList。只需执行repo.GetPeople().Select(m =&gt; new SelectListItem { ... }) 即可构建您的IEnumerable&lt;SelectListItem&gt;
    • 谢谢大家,现在工作。至于控制器线,有什么区别?
    【解决方案2】:

    如果您使用以下内容,最后一个参数指定初始文本(选项标签),因此您不需要使用虚拟 -1 值:

     Html.DropDownListFor(m => m.SelectedPersonId, 
              Model.PersonList as List<SelectListItem>, "Select   Forester -"})
    

    SelectExtensions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-01
      • 2021-06-19
      相关资源
      最近更新 更多