我发送选定列表以使用ViewBag进行查看。这是我通过ViewBag传递的get方法
public List<Dept> GetDept()
{
connection();
List<Dept> deptList = new List<Dept>();
SqlCommand com = new SqlCommand("Sp_GetDept", con);
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
con.Open();
da.Fill(dt);
con.Close();
//Bind EmpModel generic list using dataRow
foreach (DataRow dr in dt.Rows)
{
deptList.Add(
new Dept
{
DeptId = Convert.ToInt32(dr["DeptId"]),
Name = Convert.ToString(dr["Name"])
}
);
}
return deptList;
}
public ActionResult Create()
{
DeptRepo repo = new DeptRepo();
ViewBag.Dept = new SelectList(repo.GetDept(), "DeptId", "Name");
return View();
}
查看代码:
<div class="form-group">
@Html.LabelFor(model => model.Dept, "Department", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Dept", null, "--Select--", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Dept, "", new { @class = "text-danger" })
</div>
</div>
学生模特:
public class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public string Roll { get; set; }
public int DeptId { get; set; }
public virtual Dept Dept { get; set; }
}
发布方法:
[HttpPost]
public ActionResult Create(Student std)
{
try
{
if (ModelState.IsValid)
{
StudentRepo repo = new StudentRepo();
repo.AddStudent(std);
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
在post方法下拉列表中,id值在student对象中找到null。 任何人都可以告诉我如何使用mvc和ado.net检索foreignkey Id。 任何形式的帮助将不胜感激。
答案 0 :(得分:1)
您当前的代码,
@Html.DropDownList("Dept", null, "--Select--",
htmlAttributes: new { @class = "form-control" })
将为名称属性值设置为Dept
<select class="form-control" id="Dept" name="Dept">
<option value="">--Select--</option>
</select>
由于您使用Student
类作为您的httppost操作方法参数,因此对于模型绑定以将所选选项值正确映射到Student对象的DeptId
属性,您需要确保选择元素名称也是DeptId
如果您的视图是Student
类的强类型,则可以使用DropDownListFor
辅助方法
@Html.DropDownListFor(a => a.DeptId, ViewBag.Dept as IEnumerable<SelectListItem>,
"--Select--", htmlAttributes: new { @class = "form-control" })
或强>
您可以使用DropDownList
方法并将DeptId
作为第一个参数(控件的名称),并明确指定用于构建选项的集合作为第二个参数。
@Html.DropDownList("DeptId", ViewBag.Dept as IEnumerable<SelectListItem>,
"--Select--", htmlAttributes: new { @class = "form-control" })
这会将SELECT元素的name属性值设置为DeptId
,并且在提交表单时,模型绑定器将能够使用所选的选项值将其设置为DeptId
属性Student
对象(这是您的httppost操作方法参数)