我能够在 ListBoxFor 控件中显示从控制器到视图的值。但是,当我将值从一个列表框移动到另一个列表框并发布视图时,控制器端的模型不会保留列表框中的值。
这是我的模型
namespace MvcApplication1.Models
{
public class EmployeeClass
{
public int EmpCode { get; set; }
public string EmpName { get; set; }
}
public class EmployeeViewModel
{
public string Department { get; set; }
public list<EmployeeClass> AvailalableEmployee { get; set; }
public list<EmployeeClass> SelectedEmployee { get; set; }
public int [] AvailableEmpCodeArray { get; set; }
public int [] SelectedEmpCodeArray { get; set; }
}
}
这是我的控制器
namespace MvcApplication1.Controllers
{
public class EmployeeController : Controller
{
public ActionResult EmployeeDisplayTool()
{
EmployeeViewModel model = new EmployeeViewModel();
model.Department = "Techology"
model.AvailalableEmployee.Add(new Employee(1,"Emp1"));
model.AvailalableEmployee.Add(new Scenario(2,"Emp2"));
model.AvailalableEmployee.Add(new Scenario(3,"Emp3"));
model.SelectedEmployee.Add(new Scenario(4,"Emp4"));
model.SelectedEmployee.Add(new Scenario(5,"Emp5"));
model.SelectedEmployee.Add(new Scenario(6,"Emp6"));
return View(model);
}
[HttpPost]
public ActionResult EmployeeDisplayTool(EmployeeViewModel model)
{
//model.Department is populated as "Technology"
//All of the follownig collections are null.
//model.AvailalableEmployee is null.
//model.AvailableEmpCodeArray is null.
//model.SelectedEmployee is null.
//model.SelectedEmpCodeArray is null.
}
}
}
这是我的视图和 JavaScript
@using (Html.BeginForm())
{
<table id="MainTable" border="0">
<tr>
<td colspan="3">
@Html.TextBoxFor(m => Model.Department, new { id = "txtDepartment" })
</td>
</tr>
<tr>
<td>
@Html.ListBoxFor(m => Model.AvailableEmpCodeArray, new MultiSelectList(Model.AvailalableEmployee, "EmpCode", "EmpName", Model.AvailableEmpCodeArray), new { id = "lbxAvailableEmployees" })
</td>
<td>
<input type="button" id="btnSelectEmployee" value=" >> "/>
<br/>
<br/>
<input type="button" id="btnUnSelectEmployee" value=" << "/>
</td>
<td>
@Html.ListBoxFor(m => Model.SelectedEmpCodeArray, new MultiSelectList(Model.SelectedEmployee, "EmpCode", "EmpName", Model.SelectedEmpCodeArray), new { id = "lbxSelectedEmployees" })
</td>
</tr>
</table>
}
<script type="text/javascript">
$(document).ready(function()
{
$('#btnSelectEmployee').click(function(e)
{
var SelectedEmps = $('#lbxAvailableEmployees option:selected');
if (SelectedEmps.length == 0)
{
e.preventDefault();
}
$('#lbxSelectedEmployees').append($(SelectedEmps).clone());
$(SelectedEmps).remove();
e.preventDefault();
});
$('#btnUnSelectEmployee').click(function(e)
{
var SelectedEmps = $('#lbxSelectedEmployees option:selected');
if (SelectedEmps.length == 0)
{
e.preventDefault();
}
$('#lbxAvailableEmployees').append($(SelectedEmps).clone());
$(SelectedEmps).remove();
e.preventDefault();
});
});
</script>