@Html.LisboxFor Model Binding for multiple items

658 Views Asked by At

My Class is

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; }
    }

Trials is anothetr calss

 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; }
    }

in my view I amn trying to bind the ListBoxFor with Trials inseide the team

@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>

I cant get any value for Trials calss in the controller ..It shows null but I select multi values from listbox

2

There are 2 best solutions below

1
AudioBubble On

A multiple select only posts back an array of primitive values. It does not post back a collection of complex objects.

You need a view model with a property to bind the selected 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
}

then in you view

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

When you post back, Team.SelectedTrials will contain and array of the selected TrialID values.

0
Khan On

I changed the Team class as

  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; }
    }

and in View

@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>

and in my controller I was able to get the Vlaues for Selected Trials