尝试通过虚构项目学习ASP.net mvc。 当我尝试将模型中的集合中的数据从视图发送回控制器时,它将失败。 (说集合为空) 我有3个模型参与该过程:
public class Employee:BaseModel
{
// alot of properties in here left out...
public virtual ICollection<EmployeeCompetences> EmployeeCompetences { get; set; }
}
public class EmployeeCompetences: BaseModel
{
public int EmployeeId { get; set; }
public int CompetenceId { get; set; }
public virtual Competence Competence { get; set; }
public virtual Employee Employee {get; set;}
public string Level { get; set; }
}
public class Competence: BaseModel
{
public string Name { get; set; }
public string CompetenceCategory { get; set; }
}
在我的控制器中,我将一名雇员传递到具有当前能力水平的视图。
控制器:
public ActionResult Competences_Edit(int id = 0)
{
if (id == 0)
return RedirectToAction("Index");
var employee = employeeService.GetById(id);
ViewBag.Levels = levelLoader.GetAll(); //Possible values for the user to give to his competence level.
return View(employee);
}
我尝试以多种不同方式在视图中设置值。我最接近的就是通过这些。
查看:
@model PeopleApplication.BDO.Models.Employee
@using (Html.BeginForm()){
foreach (var item in Model.EmployeeCompetences)
{
<div>
<p>@item.Competence.Name</p>
@Html.DropDownListFor(model => item, new SelectList(ViewBag.Levels, "Name", "Name", item.Level), new { @class = "btn btn-outline-secondary btn-sm dropdown-toggle", @style = "background-color: white; color: black;" })
</div>
}
<div class="form-group">
<div class="col">
<input type="submit" value="Save" class="btn btn-success" style="float: right" />
</div>
</div>
}
还尝试了for循环而不是foreach。
这是我的控制器中的post方法:
[HttpPost]
public ActionResult Competences_Edit(Employee employee)
{
if (ModelState.IsValid)
{
employeeService.UpdateEntity(employee);
return RedirectToAction("Index", new { id = employee.Id });
}
return RedirectToAction("Competences_Edit", employee.Id);
}
在调试时,post方法employee中的employees能力集合仅为空。 我要去哪里错了?我有一个类似的页面,可以用相同的方式进行编辑,但是该页面在模型中不包含集合,因此该方法可以正常工作。