MVC 4下拉列表不能添加到模型中
本文关键字:模型 添加 不能 下拉列表 MVC | 更新日期: 2023-09-27 18:14:57
嗨,我是MVC 4的新手,在尝试使用Html.DropDownList时遇到了一个错误。
这是我当前的代码。
Model for Jobs:
namespace Payroll.CORE
{
public class Job
{
public int JobID { get; set; }
public string JobTitle { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
}
员工模型:
public int EmployeeID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public int PhoneNumber { get; set; }
public int CellNumber { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public int PostalCode { get; set; }
public string BankName { get; set; }
public int BankAccountNumber { get; set; }
public string PayInterval { get; set; }
public double NormalRate { get; set; }
public double OvertimeRate { get; set; }
public double SetHours { get; set; }
public System.DateTime DateOfEmployment { get; set; }
public System.DateTime LastPaymentRecieved { get; set; }
public string Active { get; set; }
public int JobID { get; set; }
public virtual ICollection<Absent> Absents { get; set; }
public virtual ICollection<Bonus> Bonuses { get; set; }
public virtual Job Job { get; set; }
public virtual ICollection<Holiday> Holidays { get; set; }
public virtual ICollection<HoursWorked> HoursWorkeds { get; set; }
public virtual ICollection<Payrolls> Payrolls { get; set; }
public virtual ICollection<Deduction> Deductions { get; set; }
视图:
<div class="editor-label">
@Html.LabelFor(model => model.JobID)
</div>
<div class="editor-field">
@Html.DropDownList("ListSL")
</div>
控制器:
[HttpGet]
public ActionResult Create()
{
List<SelectListItem> jobs = new List<SelectListItem>();
List<Job> list = bll.GetJobCatergories();
foreach (var a in list)
{
jobs.Add(new SelectListItem { Text = a.JobTitle, Value = a.JobID.ToString() });
}
ViewBag.ListSL = jobs;
return View();
}
我现在无法将JobID的值获取到我的模型中。我试过使用@Html。DropDownListFor,但不能让它与SelectListItem填充。
我真的没有问题,让它工作与隐藏字段或任何东西,所以任何帮助将非常感激。
提前感谢。
编辑:抱歉应该说得更清楚一点。我正在创建一个员工,该员工被分配了一份工作。因此,我试图将所选项目列表值添加到Employee中的值int JobID。
值也显示在下拉列表中,我需要在提交时将所选值添加到员工模型。
好的,现在模型已经就绪,试试:
@Html.DropDownListFor(mdl => mdl.Job.JobID,
new SelectList(ViewBag.ListSL,
"Value",
"Text",
Model.JobID),
"-- Please Select --")
我还想补充一点,就我个人而言,我不喜欢使用ViewBag,因为你失去了静态类型,因此在这种情况下需要将其转换回SelectList。每当我需要一个下拉列表时,我在模型上有一个静态属性,它返回将填充下拉列表的所有项,因此我最终得到,例如:
new SelectList(Model.AllJobs,....)
因为我看不到你的模型…
@Html.DropDownListFor(
x => x.JobIdSelected,
new SelectList(Model.JobId, "Value", Model.JobId)
)
在你的模型中创建一个属性,JobIdSelected,它将被绑定。
注意,您将丢失原始选择列表,因此如果您有任何模型错误,您将需要将列表重新发送回视图。
应该是
@Html.DropDownListFor(m => m.JobID, (IEnumerable<SelectListItem>)ViewBag.ListSL)
使用ViewBag将所选值绑定到JobID属性。ListSL作为选项