在MVC应用程序中,我有一个显示任务的视图。任务应由分配给他们的员工过滤。员工将显示在下拉列表中。
@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();"
})
}
我有一个带有ActionResult的TaskController,从表单中获取数据:
[HttpPost]
public ActionResult EmployeeDropUsed(int id)
{
Employee e = er.GetById(id);
return LoadControls(er.GetAll(), e.Tasks.ToList());
}
ViewModel看起来像这样
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; }
}
问题是我不知道如何从退回到控制器中获取所选值。我尝试在模型中使用DropDownListFor和EmployeeId属性:
@Html.DropDownListFor(m => Model.EmployeeId, Model.Employees, "Select Employee")
public int EmployeeId { get; set; }
结果是id始终为0.
答案 0 :(得分:5)
虽然lambda表达式不正确吗?不应该是
@Html.DropDownListFor(m => m.EmployeeId ....
而不是
@Html.DropDownListFor(m => Model.EmployeeId
答案 1 :(得分:2)
问题是,您的EmployeeDropUsed
操作正在查找名为id
的参数,而您发送的参数为EmployeeId
。将EmployeeDropUsed
操作上的参数名称更改为employeeId
或将EmployeeId
上的TaskModel
属性更改为id
。
如果您更改TaskModel
属性,则应该有效:
@Html.DropDownListFor(m => m.id, Model.Employees, "Select Employee")
如果您更改EmployeeDropUsed
参数,则该功能应该有效:
@Html.DropDownListFor(m => m.EmployeeId, Model.Employees, "Select Employee")