我是Asp.Net MVC 4的新手,我的问题是
是否可以在不使用jquery或javascript的情况下将View下拉列表值从View发送到Controller。
我总是将Department
的值设为null
我的模型如下
public partial class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public Nullable<int> Age { get; set; }
[DisplayFormat(DataFormatString="{0:d}",ApplyFormatInEditMode=true)]
public Nullable<System.DateTime> DOB { get; set; }
public string Address { get; set; }
public Nullable<int> DepartmentId { get; set; }
public virtual Department Department { get; set; }
}
我的控制器如下
[HttpPost]
public ActionResult Edit(Employee modelEmployee)
{
if (ModelState.IsValid)
{
db.Employees.Add(modelEmployee);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(modelEmployee);
}
我的观点如下
@Html.DropDownListFor(m=>m.Department,new SelectList(Model.Department,"Id","Name",
Model.DepartmentId),"Select Department")
答案 0 :(得分:0)
使用ViewBag在控制器中创建选择项目:
[HttpGet]
public ActionResult Edit(int id)
{
var employee = db.Employees.Find(id);
CreateDepartmentsDropdown();
return View(employee);
}
private void CreateDepartmentsDropdown()
{
ViewBag.Departments = db
.Departments
.ToList()
.Select(c => new SelectListItem
{
Text = c.Name,
Value = c.Id.ToString()
});
}
查看:
@Html.DropDownList("DepartmentId", (IEnumerable<SelectListItem>)ViewBag.Departments,
"-- Select department --")
答案 1 :(得分:0)
问题似乎已经解决了,但更简单的是传递绑定到下拉列表的相同集合属性而不是传递属性类型来保存所选数据的错误。
@devqon使用普通的html帮助程序提供了解决方案,但也可以通过强类型帮助程序实现。
@Html.DropDownListFor(m=>m.Department,new SelectList(Model.Department,"Id","Name", Model.DepartmentId),"Select Department")
将上述代码替换为
@Html.DropDownListFor(m=>m.DepartmentId,new SelectList(Model.Department,"Id","Name", Model.DepartmentId),"Select Department")