【问题标题】:@Html.LisboxFor Model Binding for multiple items@Html.LisboxFor 模型绑定多个项目
【发布时间】:2014-11-28 06:50:08
【问题描述】:

我的班级是

public partial class Team
    {
        public int TeamId { get; set; }
        public string TeamName { get; set; }
        public string TeamDescription { get; set; }
        public virtual IList<Trials> Trials { get; set; }
    }

试炼是另一个类

 public partial class Trials
    {

        public int TrialID { get; set; }
        public string Name { get; set; }
        public int TrialTyp_RefID { get; set; }
        public bool isChk { get; set; }

        public virtual ICollection<Team> Team { get; set; }
    }

在我看来,我正在尝试将 ListBoxFor 与团队内部的 Trials 绑定

@model Trials.Classes.Team
  <td colspan="2">          
              @Html.ListBoxFor(model=> model.Trials,
                      new SelectList(ViewBag.trials,"TrialID", "Name"),                   
                        new { @class = "chosen-select", data_placeholder = "Select Trials...", style = "width:500px;", tabindex = "4" }
                        )
           </td>

我无法在控制器中获得 Trials calss 的任何值。它显示为 null,但我从列表框中选择了多个值

【问题讨论】:

    标签: asp.net-mvc-4 model-binding html.listboxfor


    【解决方案1】:

    多选仅回发一组原始值。它不会回发复杂对象的集合。

    您需要一个带有属性的视图模型来绑定选定的Trials

    public class TeamVM
    {
      public int TeamId { get; set; }
      ....
      public int[] SelectedTrials { get; set; }
      public SelectList Trials { get; set; } // Assign this in your controller rather than using ViewBag
    }
    

    那么在你看来

    @Html.ListBoxFor(m => m.SelectedTrials, Model.Trials)
    

    当您回帖时,Team.SelectedTrials 将包含所选TrialID 值的数组。

    【讨论】:

    • 谢谢斯蒂芬....再次感谢您澄清我们不能这样做...我已经尝试过您对字符串数组的建议,并且能够获得字符串数组中的值。 ....但是我想知道如何将它直接与 Team 类中的 Trials 对象绑定...再次感谢
    【解决方案2】:

    我将 Team 类更改为

      public partial class Team
            {
                public int TeamId { get; set; }
                public string TeamName { get; set; }
                public string TeamDescription { get; set; }
                public virtual IList<Trials> Trials { get; set; 
                public int[] AuthorisedTrials { get; set; }
        }
    

    在视图中

    @model Trials.Classes.Team
      <td colspan="2">          
                  @Html.ListBoxFor(model=> model.AuthorisedTrials ,
                          new SelectList(ViewBag.trials,"TrialID", "Name"),                   
                            new { @class = "chosen-select", data_placeholder = "Select Trials...", style = "width:500px;", tabindex = "4" }
                            )
               </td>
    

    在我的控制器中,我能够获得选定试验的 Vlaues

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-12
      • 2022-11-28
      • 1970-01-01
      • 2012-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多