In a MVC application, I have a view showing tasks. The tasks should be filtered by employees to which they are assigned. Employees are shown in a dropdownlist.
@using (Html.BeginForm("EmployeeDropUsed", "Task", new { id = ?? }))
{
@Html.DropDownList(
"EmployeeDrop", new SelectList(Model.Employees, "Id", "EmployeeName"), "Select employee",
new
{
onchange = @"
var form = document.forms[0];
form.submit();"
})
}
I have a TaskController with an ActionResult, taking the data from the form:
[HttpPost]
public ActionResult EmployeeDropUsed(int id)
{
Employee e = er.GetById(id);
return LoadControls(er.GetAll(), e.Tasks.ToList());
}
The ViewModel looks like this
public class TaskModel
{
public TaskModel(List<Employee> employees, List<Task> tasks)
{
Employees = employees;
Tasks = tasks;
}
public List<Task> Tasks { get; set; }
public List<Employee> Employees { get; set; }
}
The problem is I don´t know how to get the selected value from the drop back to the controller. I tried using DropDownListFor and an EmployeeId property in the model:
@Html.DropDownListFor(m => Model.EmployeeId, Model.Employees, "Select Employee")
public int EmployeeId { get; set; }
The result is that id is always 0.
The problem is that your
EmployeeDropUsedaction is looking for a parameter namedidand the parameter you are sending it isEmployeeId. Either change the parameter name on theEmployeeDropUsedaction toemployeeIdor change theEmployeeIdproperty onTaskModeltoid.If you change the
TaskModelproperty this should work:If you change the
EmployeeDropUsedparameter this should work: