Asp.net mvc 4 在Asp.NETMVC4中将dropdownlist值从视图传递到控制器,而不使用jquery或javascript?
我是Asp.NETMVC4新手,我的问题是 是否可以在不使用jquery或javascript的情况下将下拉列表值从视图发送到控制器。 我总是把Department的值设为null 我的模型如下Asp.net mvc 4 在Asp.NETMVC4中将dropdownlist值从视图传递到控制器,而不使用jquery或javascript?,asp.net-mvc-4,Asp.net Mvc 4,我是Asp.NETMVC4新手,我的问题是 是否可以在不使用jquery或javascript的情况下将下拉列表值从视图发送到控制器。 我总是把Department的值设为null 我的模型如下 public partial class Employee { public int Id { get; set; } public string Name { get; set; } public Nullable<int> Age { get; set; }
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")
我的看法如下
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")
使用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()
});
}
视图:
这个问题似乎已经解决了,但更简单的是,传递绑定到下拉列表的同一个集合属性,而不是传递用于保存所选数据的属性类型,这是一个错误 @devqon提供了使用普通html助手的解决方案,但也可以通过强类型助手来实现 @Html.DropDownListForm=>m.Department,新建SelectListModel.Department,Id,名称,Model.DepartmentId,选择部门 将上述代码替换为
@Html.DropDownListForm=>m.DepartmentId,new SelectListModel.Department,Id,Name,Model.DepartmentId,Select Department您不能将Select或任何其他控件绑定到复杂对象。绑定到ProeProperty DepartmentId,但您不能创建SelectList模型。Department是单个对象,而不是CollectionArh。像OP一样使用强类型助手!设置所选属性是无意义的所选选项是属性DepartmentId的值,它可以是ViewBag.Departments=new SelectListdb.Departments,ID,Name;