I am creating Multi-Select able List Box. I am able to successfully render items from model to list box. Following is my code:
Properties
public IEnumerable<SelectListItem> carTypes { get; set; }
public IEnumerable<string> selectedCarTypes { get; set; }
Create Action
public ActionResult Create()
{
List<SelectListItem> selectListItem = new List<SelectListItem>();
foreach(CarType type in db.CarTypes)
{
SelectListItem item = new SelectListItem()
{
Text = type.Name,
Value = type.Id.ToString()
};
selectListItem.Add(item);
}
Assigning assign = new Assigning ();
assign.carTypes = selectListItem;
return View(assign);
}
View
@Html.ListBoxFor(model=>model.selectedCarTypes,Model.carTypes)
The problem is the edit action. I have been trying to highlight all the List box in the Edit View
which are selected for the particular AssignId
e.g. In list box there are three items: Hyundai, Toyota, and BMW and I select BMW and Toyota and Create Assigning. Now When I come back to Edit View it should highlight BMW and Toyota.
I took reference from here, but did not work for me. Is there any solution for this problem?
Modification: Here is my Edit Action
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Assigning assign = db.Assigning.Find(id);
if (assign == null)
{
return HttpNotFound();
}
return View(assign);
}
You are not setting up your models when Edit:
Model.carTypes
should be List<SelectListItem>
of all CarTypes and
Model.selectedTypes
should be List<string>
of all selected values