You have quite few options on front end . Razor, Angular, Jquery... To simplfy things in following example i have used Razor view. I dont think you need to pass Skills as a strongly type object as you only need Id of selected Skills . Also in the example i have the skills list static / hard coded into razor view, ideally it should be bound from backend.
Saying that lets assume our Employee View Model as it follows
public class EmployeeViewModel
{
public EmployeeViewModel()
{
SelectedSkills=new List<int>();
}
public int Id { get; set; }
public string Name { get; set; }
public List<int> SelectedSkills { get; set; }
}
public class Skills
{
public int Id { get; set; }
public string Name { get; set; }
}
Then our Controller (EmployeeController.cs) would be .(please ignore the EF logic after data is bound to class)
public class EmployeeController : Controller
{
public ActionResult Index()
{
return View("Employee",new EmployeeViewModel());
}
[HttpPost]
public ActionResult AddEmp(EmployeeViewModel employee)
{
var idOfEmployee=AddEmployee(employee);
foreach (var item in employee.SelectedSkills)
{
AddSkill(idOfEmployee,item);
}
return View("Employee");
}
private void AddSkill(int idOfEmployee, int skillId)
{
// your EF logic
}
private int AddEmployee(EmployeeViewModel emp)
{
// your EF logic, get your id of the inserted employee
return 0;
}
}
Then our Employee.cshtml view could be
@using System.Web.UI.WebControls
@using WebApplication4.Controllers
@model WebApplication4.Controllers.EmployeeViewModel
@{
ViewBag.Title = "Employee";
}
<h2>Employee</h2>
@{var listItems = new List<Skills>
{
new Skills { Id = 0,Name="Java" },
new Skills { Id = 1,Name="C++" },
new Skills { Id = 2,Name="Fortran" }
};
}
@using (Html.BeginForm("AddEmp", "Employee"))
{
@Html.TextBoxFor(m => m.Name, new { autofocus = "New Employee" })
<br/>
@Html.ListBoxFor(m => m.SelectedSkills,
new MultiSelectList(listItems, "Id", "Name",@Model.SelectedSkills)
, new { Multiple = "multiple" })
<input type="submit" value="Submit" class="submit"/>
}
select>only posts back one value - the value of the selected option, and your method need to bepublic ActionResult AddEmp(int EmpSkills)to match the name of your form control. but why are you doing this. Use a model and bind to your model using the strong typesHtmlHelpermethods (and if you want to post multiple values, then the dropdownlist needs themultipleattribute)IEnumerable<int> SelectedSkillsandIEnumerable<SelectListItem> SkillsListand in the view@Html.DropDownListFor(m => m.SelectedSkills, Model.SkillsList)(or for a multiple select, thenListBoxFor(m => m.SelectedSkills, Model.SkillsList)