0
Reply

how to set the selected values back in listboxfor in MVC4

lakshmi sowmya

lakshmi sowmya

Feb 20 2014 12:45 AM
5.3k
Hi,
            I am new to MVC, in our application we are using listbox for multiple select options.I was able to select multiple options successfully and saved them in database. but unable to display them back into the listbox.
 
Model:
                   
[Display(Name = "Select Section")]
[Required(ErrorMessage="Select any Section")]
public string[] Sections { get; set; }
public List<Section> SelSection { get; set; }
 ---------------------------------------------------
public class Section
{
[MustBeSelected(ErrorMessage = "select any Section")]
public int SectionId { get; set; }
public string Section_Name { get; set; }
}
 
Controller: 
var empInfo = (from objemp in objHeritageEntities.hfl_employee where objemp.Id == empId select objemp).FirstOrDefault();
EmployeeRegistration objempInfo = new EmployeeRegistration();
 
string[] Sections = empInfo.Section_Id.Split(',');
int id;
List<Section> selSections = new List<Section>();
foreach (var Id in Sections)
{
id = Convert.ToInt32(Id);
Section Item = new Section();
Item.SectionId = id;
selSections.Add(Item);
}
// ViewBag.SelSection = selSections;
objempInfo.SelSection = selSections;
 
View: 
<td>
@Html.LabelFor(m => m.Sections)
</td>
<td>
@Html.ListBoxFor(m => m.Sections, new MultiSelectList(ViewBag.Sections, "SectionId", "Section_Name", Model.SelSection), new { style = "width:210px" })
</td>
<td>
@Html.ValidationMessageFor(m => m.Sections)
</td>
 
I have tried like this,I am able to get the data in Model.SelSection, but those Id's are not getting selected. Please help me where I went wrong.