Im trying to use IEnumerable so it holds multiple selections so a user can choose more then one value in my listbox.
This is how my ViewModel looks like:
public class CreateViewModel
{
public IEnumerable<string> SelectedValues { get; set; }
public IEnumerable<CoreValue> CoreValues { get; set; }
}
This is my GET in my controller:
public ActionResult Create()
{
CreateViewModel model = new CreateViewModel();
model.CoreValues = AdminRepository.GetAllCoreValues();
return View(model);
}
This how my view looks like:
@Html.ListBoxFor(m => m.SelectedValues, new MultiSelectList(Model.CoreValues, "Id", "Name"))
How do I code my POST action so that SelectedValues will be used to contain the selected values on the post?
Before Ienumerable I had string declared to CoreValueName in my ViewModel and I did something like this in my POST action which worked perfectly but now I changed it to Ienumerable and I have am not sure how to code so my selectedvalues will be used to contain the selected values in my post.
Question question = new Question();
var CoreValueID = int.parse(model.CoreValueName);
var GetAllCoreValuesID = AdminRep.GetByCoreValueID(CoreValueID);
question.CoreValue.Add(GetAllCoreValuesID);
AdminRepository.AddQuestion(question);
AdminRepository.save();
This version of my POST action works perfectly beacuse model.SubjectType is declared as string in my Viewmodel:
[HttpPost]
public ActionResult Create(AdminCreateViewModel model)
{
Question question = new Question();
var SubjectTypeID = int.Parse(model.SubjecTypeName);
var GetAllSubjecTypesID = AdminRep.GetBySubjectTypeID(SubjectTypeID);
question.SubjectType.Add(GetAllSubjecTypesID);
AdminRep.AddQuestion(question);
AdminRep.save();
}
This version of my Post action is not working beacuse Model.Selectedvalues is declared as Ienumerable string in my ViewModel. I tried to int.parse my model.SelectedValues but that doesnt work with Ienumerable. And GetByCoreValueID method takes int as argument so I have no idea how do to this. Do I need foreach?
[HttpPost]
public ActionResult Create(AdminCreateViewModel model)
{
Question question = new Question();
var CoreValueID = model.SelectedValues;
var GetAllCoreValuesID = AdminRep.GetByCoreValueID(CoreValueID); //
question.CoreValue.Add(GetAllCoreValuesID);
AdminRep.AddQuestion(question);
AdminRep.save();
Thanks in advance!
You could have your POST controller action take the view model as argument. Then the
SelectedValuesproperty will contain a list of values that the user selected: