3
我试图绑定mvc3中数据库的下拉列表。如何将数据库中的值绑定到MVC中的下拉列表3
我有两个表。 tblEmp: 的EmpID(PK), 的ename, 年龄, 地址, EMAILID, DEPTID(FK)。
tblDept DEPTID(PK), DEPTNAME, DeptHead。
我试图绑定创建一个雇员应用程序与雇员的基本细节 姓名,年龄,地址,EmailID和部门名称。我试图绑定另一个表中的Dept Name下拉列表。
这是我的模型:
namespace MvcEmployeeApplication.Models
{
public class UandPcompare
{
public int EmpID { get; set; }
public string EName { get; set; }
public int Age { get; set; }
public string Address { get; set; }
public string EmailID { get; set; }
public int DeptID { get; set; }
public string DeptName { get; set; }
public string DeptHead { get; set; }
public IList<SelectListItem> Drp_DeptNames { get; set; }
}
}
这是控制器:
[HttpGet]
public ActionResult Create()
{
FillDeptName();
return View();
}
[HttpPost]
public ActionResult Create(tblEmployee tblEmp)
{
test.Entry(tblEmp).State = System.Data.EntityState.Added;
test.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult FillDeptName()
{
UandPcompare filldeptNme = new UandPcompare();
filldeptNme.Drp_DeptNames = (from DptName in test.tblDepts
select new SelectListItem()
{
Text = DptName.DeptName,
Value = SqlFunctions.StringConvert((double)DptName.DeptID)
}).ToList<SelectListItem>();
return View("Create");
}
这是MyView的:
@model MvcEmployeeApplication.Models.UandPcompare
@{
ViewBag.title = "Edit";
}
<h2> Create </h2>
@using (Html.BeginForm())
{
<fieldset>
<legend> Create </legend>
<div>
Employee ID: @Html.DisplayFor(model => model.EmpID)
</div>
<div>
Employee Name: @Html.EditorFor(model => model.EName)
</div>
<div>
Email-ID: @Html.EditorFor(model => model.EmailID)
</div>
<div>
Address: @Html.EditorFor(model => model.Address)
</div>
<div>
Dept Name: @Html.DropDownList("DeptName", Model.Drp_DeptNames, "Select")
</div>
<p>
<input type="submit" value="Create" />
</p>
<div>
@Html.ActionLink("Back to Index", "Index");
</div>
我认为要做到这一点的最好办法是编写JavaScript这将调用'Action'方法,这反过来将返回对象的JSON数组。然后,您可以使用JQUERY将这些绑定到下拉菜单。 – Nilesh
不要以为它的好主意,什么时候需要ajax ajax什么时候可以通过SelectList只有动作 –