嘿伙计们,我需要你的帮助,我在MVC中有一个创建员工表格。我填写表单并从下拉列表中选择,当我单击提交时,每个其他字段返回除下拉列表之外的值。我似乎无法解决问题。这就是表格的样子。
这是CreateEmployee模型
public class CreateEmployee
{
public int Id { get; set; }
public string FullName { get; set; }
[Required]
public string Notes { get; set; }
public int Department { get; set; }
public IEnumerable<AngTestDepartment> Departments { get; set; }
public bool PerkCar { get; set; }
public bool PerkStock { get; set; }
public bool PerkSixWeeks { get; set; }
public string PayrollType { get; set; }
}
动作控制器
public ActionResult Employee(){
using (var db = new DepartmentDbContext())
{
var model = new CreateEmployee();
model.Departments = db.AngTestDepartments.ToList();
return View(model);
} }
和视图
@using (Html.BeginForm("CreateEmployee", "Employee", FormMethod.Post))
{ @ Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.FullName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FullName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.FullName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Notes, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Notes, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Notes, "", new { @class = "text-danger" })
</div>
</div>
// the drop down doesnt return a value on submit
<div class="form-group">
@Html.LabelFor(model => model.Department, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.Departments,
Model.Departments.Select(d => new SelectListItem()
{
Value = d.id.ToString(),
Text = d.Department
}
), new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Department, "", new { @class = "text-danger" })
</div>
</div> }
并且要求提交
的操作结果 public ActionResult CreateEmployee(CreateEmployee newEmployee)
{
DbEmployeeTable.DbEmployeeTable_EmployeeTable(newEmployee);
return RedirectToAction("Employees");
}
非常感谢你的帮助。
答案 0 :(得分:0)
而不是
@Html.DropDownListFor(m => m.Departments,
试试这个......
@Html.DropDownListFor(m => m.Department,
这应该将部门Id作为选定值的int返回。
答案 1 :(得分:0)
将下拉列表代码更改为:
@Html.DropDownListFor(m => m.Department, new SelectList(Model.Departments.Select(d => new SelectListItem()
{
Value = d.id.ToString(),
Text = d.Department
}
)), new { htmlAttributes = new { @class = "form-control" } })
Dropdownlistfor的第一个参数应该是你想要获得的值,而第二个参数是一个选择列表将在以后保存与持久性相关的麻烦。
顺便说一句,我还会将Model.Departments.Select结果作为一个模型属性,这样你就不会混淆你的视图,但这只是一个风格问题。