I have created 2 multiselect list for Contact Group details and employee details in a create() function, while the view for both of them are different at runtime it appears in 1 textbox.. Not sure why is it happening?
I tried changing the view, and the controller as well here is the code for my controller:
// GET: DistributionLists/Create
public ActionResult Create()
{ //LIST FOR CONTACT DETAILS
var contact = db.Contact;
List<SelectListItem> items = new List<SelectListItem>();
foreach (var item in contact)
{
items.Add(new SelectListItem
{
Value = item.EmployeeId.ToString(),
Text = item.EmployeeName.ToString(),
});
};
ViewBag.Contacts = items;
// ViewBag.EmployeeId = new SelectList (db.Contact, "EmployeeId","EmployeeName");
//LIST FOR CONTACT GROUP DETAILS
var cg = db.ContactGroup;
List<SelectListItem> ims = new List<SelectListItem>();
foreach (var im in cg)
{
items.Add(new SelectListItem
{
Value = im.ContactGroupID.ToString(),
Text = im.ContactGroupName.ToString(),
});
};
ViewBag.cg = ims;
return View();
}
Here is the code for my View of the create page:
<div >
@Html.LabelFor(model => model.EmployeeId, "EmployeeName", htmlAttributes: new { @class = "control-label col-md-2" })
<div >
@Html.DropDownList("Contacts", ViewBag.Contacts as List<SelectListItem>, new { @class = "form-control", multiple = "multiple" })
@Html.ValidationMessageFor(model => model.EmployeeId, "", new { @class = "text-danger" })
</div>
</div>
<div >
@Html.LabelFor(model => model.ContactGroupId, "ContactGroupName", htmlAttributes: new { @class = "control-label col-md-2" })
<div >
@Html.DropDownList("ContactGroupId", ViewBag.cg as List<SelectListItem>, new { @class = "form-control", multiple = "multiple" })
@Html.ValidationMessageFor(model => model.ContactGroupId, "", new { @class = "text-danger" })
</div>
</div>
CodePudding user response:
You have created two list in controller side. You have added all items in first listing
List<SelectListItem> ims = new List<SelectListItem>();
foreach (var im in cg)
{
ims.Add(new SelectListItem
{
Value = im.ContactGroupID.ToString(),
Text = im.ContactGroupName.ToString(),
});
};
ViewBag.cg = ims;
just change items.Add into ims.Add in for loop
CodePudding user response:
while the view for both of them are different at runtime it appears in 1 textbox..
From your code, you set all into items
List<SelectListItem> ims = new List<SelectListItem>();
foreach (var im in cg)
{
items.Add(new SelectListItem
{
Value = im.ContactGroupID.ToString(),
Text = im.ContactGroupName.ToString(),
});
};
ViewBag.cg = ims;
Change items.Add
intoims.Add
like :
ims.Add(new SelectListItem
{
Value = im.ContactGroupID.ToString(),
Text = im.ContactGroupName.ToString(),
});