首页 > 解决方案 > 无法使用 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。任何形式的帮助将不胜感激。

标签: asp.net-mvcado.nethtml.dropdownlistfor

解决方案


您当前的代码,

@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 操作方法参数,为了模型绑定正确地将选定的选项值映射到DeptIdStudent 对象的属性,您需要确保您的选择元素名称也是DeptId

如果您的视图是Student类的强类型,您可以使用DropDownListFor辅助方法

@Html.DropDownListFor(a => a.DeptId, ViewBag.Dept as IEnumerable<SelectListItem>, 
                           "--Select--", htmlAttributes: new { @class = "form-control" })

或者

您可以使用DropDownListmethod 和 giveDeptId作为第一个参数(控件的名称),并明确指定用于构建选项的集合作为第二个参数。

@Html.DropDownList("DeptId", ViewBag.Dept as IEnumerable<SelectListItem>, 
                    "--Select--", htmlAttributes: new { @class = "form-control" })

这将呈现带有 name 属性值的 SELECT 元素,DeptId当提交表单时,模型绑定器将能够使用选定的选项值将其设置为对象的DeptId属性Student(这是您的 httppost 操作方法参数)


推荐阅读