asp.net-mvc - 无法使用 mvc 和 ado.net 检索模型中的 DropdownList 值
问题描述
我正在发送选择列表以使用 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 方法 dropdownlist id 值在学生对象中发现 null。谁能告诉我如何使用 mvc 和 ado.net 检索外键 ID。任何形式的帮助将不胜感激。
解决方案
您当前的代码,
@Html.DropDownList("Dept", null, "--Select--",
htmlAttributes: new { @class = "form-control" })
将为名称属性值设置为的 SELECT 元素生成 HTML 标记Dept
<select class="form-control" id="Dept" name="Dept">
<option value="">--Select--</option>
</select>
由于您使用Student
该类作为您的 httppost 操作方法参数,为了模型绑定正确地将选定的选项值映射到DeptId
Student 对象的属性,您需要确保您的选择元素名称也是DeptId
如果您的视图是Student
类的强类型,您可以使用DropDownListFor
辅助方法
@Html.DropDownListFor(a => a.DeptId, ViewBag.Dept as IEnumerable<SelectListItem>,
"--Select--", htmlAttributes: new { @class = "form-control" })
或者
您可以使用DropDownList
method 和 giveDeptId
作为第一个参数(控件的名称),并明确指定用于构建选项的集合作为第二个参数。
@Html.DropDownList("DeptId", ViewBag.Dept as IEnumerable<SelectListItem>,
"--Select--", htmlAttributes: new { @class = "form-control" })
这将呈现带有 name 属性值的 SELECT 元素,DeptId
当提交表单时,模型绑定器将能够使用选定的选项值将其设置为对象的DeptId
属性Student
(这是您的 httppost 操作方法参数)
推荐阅读
- javascript - 为什么 useReducer 钩子重新渲染它的组件两次?
- python - NameError:名称“isfile”未定义
- objective-c - 从 Objc 超类继承的 Swift 子类中未调用 viewDidLoad
- json - 响应正文是字符串类型,如何将其更改为 JSON 对象
- angular - Angular 10 通用 | amcharts 4:为什么服务器会尝试加载图表?
- ios - iOS/Xcode:Koloda 框架:在隐式展开 Optional 值时意外发现 nil
- java - JPA/Hibernate:保存一个包含实体列表的实体,这些实体在对象层次结构中保存一个二维对象数组
- react-redux - 你如何从 react-redux 存储中取回数据?
- reactjs - 在检查状态之前等待 thunk 完成 HTTP 请求
- java - 使用大型数据集生成 Excel 报告