Reputation: 8150
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.
Upvotes: 3
Views: 9864
Reputation: 5534
The problem is that your EmployeeDropUsed
action is looking for a parameter named id
and the parameter you are sending it is EmployeeId
. Either change the parameter name on the EmployeeDropUsed
action to employeeId
or change the EmployeeId
property on TaskModel
to id
.
If you change the TaskModel
property this should work:
@Html.DropDownListFor(m => m.id, Model.Employees, "Select Employee")
If you change the EmployeeDropUsed
parameter this should work:
@Html.DropDownListFor(m => m.EmployeeId, Model.Employees, "Select Employee")
Upvotes: 2
Reputation: 163
Isn't that lambda expression incorrect though? Shouldn't it be
@Html.DropDownListFor(m => m.EmployeeId ....
instead of
@Html.DropDownListFor(m => Model.EmployeeId
Upvotes: 5