如何获取mvc下拉列表选中的值

时间:2018-04-01 13:18:06

标签: c# asp.net-mvc dropdownlistfor

我正在开发一个MVC项目,我在Employee个对象上进行CRUD(创建/读取/更新/删除)操作。

问题在于:我正在使用DepartmentName的下拉列表分配给员工,当我编辑员工时,我希望在部门下拉列表中获得员工的选定值先前被分配给他。

以下是代码:

主视图

<table class="table" id="Grid">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.Name)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.GenderName)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.DepartmentName)
    </th>
    <th></th>
</tr>

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.GenderName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.DepartmentName)
        </td>

        @if (Context.User.IsInRole("Admin"))
        {
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.Id })

                @Html.ActionLink("Delete", "Delete", new { id = item.Id }, new { onclick = "return confirm('Are sure wants to delete?');" })
            </td>
        }
    </tr>
}

DBHelper

public List<Emloyee> GetEmployees()
{
    connection();
    List<Emloyee> employeelist = new List<Emloyee>();


    SqlCommand cmd = new SqlCommand("GetEmployeeDetails", con);
    cmd.CommandType = CommandType.StoredProcedure;
    SqlDataAdapter sd = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();


    con.Open();
    sd.Fill(dt);
    con.Close();

    foreach (DataRow dr in dt.Rows)
    {
        employeelist.Add(
            new Emloyee
            {
                Id = Convert.ToInt32(dr["Id"]),
                Name = Convert.ToString(dr["Name"]),
                GenderName = Convert.ToString(dr["GenderName"]),
                DepartmentName = Convert.ToString(dr["DepartmentName"])
            });
    }
    return employeelist;
}

控制器

public ActionResult Edit(int id)
{
    EmployeeDB edb = new EmployeeDB();
    var depart = edb.GetDepartment();
    ViewBag.DepartmentId = new SelectList(depart, "DepartmentId", "DepartmentName");


    return PartialView(edb.GetEmployees().Find(cmodel => cmodel.Id == id));
}

修改视图

<div class="form-group">
    @Html.LabelFor(model => model.DepartmentName, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("DepartmentId",(SelectList)ViewBag.DepartmentId, new { @class = "form-control" })

    </div>
</div>

2 个答案:

答案 0 :(得分:1)

如前面评论中所述,您的员工模型不包含departmentId,在模型中包含departmentId。我怀疑这是你无法在编辑视图上查看部门的原因。我相信下面的代码片段可以解决问题。

public List<Emloyee> GetEmployees()
{
    connection();
    List<Emloyee> employeelist = new List<Emloyee>();


    SqlCommand cmd = new SqlCommand("GetEmployeeDetails", con);
    cmd.CommandType = CommandType.StoredProcedure;
    SqlDataAdapter sd = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();


    con.Open();
    sd.Fill(dt);
    con.Close();

    foreach (DataRow dr in dt.Rows)
    {
        employeelist.Add(
            new Emloyee
            {
                Id = Convert.ToInt32(dr["Id"]),
                Name = Convert.ToString(dr["Name"]),
                GenderName = Convert.ToString(dr["GenderName"]),
                DepartmentName = Convert.ToString(dr["DepartmentName"])
                DepartmentId = Convert.ToInt32(dr["DepartmentId "])
            });
    }
    return employeelist;
}

控制器操作

public ActionResult Edit(int id)
{
    EmployeeDB edb = new EmployeeDB();
    var depart = edb.GetDepartment();
    ViewBag.Departments = new SelectList(depart, "DepartmentId", 
  "DepartmentName");


    return PartialView(edb.GetEmployees().Find(cmodel => cmodel.Id == id));
}

查看:

<div class="form-group">
    @Html.LabelFor(model => model.DepartmentName, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("DepartmentId",(SelectList)ViewBag.Departments, new { @class = "form-control" })

    </div>
</div>

答案 1 :(得分:0)

您可以将构造函数设置为在默认值selectList

时覆盖第四个参数
ViewBag.DepartmentId = new SelectList(depart, "DepartmentId", "DepartmentName",[setYourDefaultValue]);

SelectList

修改

DropDownList需要将SelectListItem设为null

@Html.DropDownList("DepartmentId",null, new { @class = "form-control" })

您可以在asp.net MVC selectList

上看到源代码

如果使用此覆盖方法。

DropDownList(HtmlHelper, String, IEnumerable<SelectListItem>, IDictionary<String, Object>)

您需要将selectList设置为null,以获取默认值。

private static MvcHtmlString SelectInternal(this HtmlHelper htmlHelper, ModelMetadata metadata,
    string optionLabel, string name, IEnumerable<SelectListItem> selectList, bool allowMultiple,
    IDictionary<string, object> htmlAttributes)
{
    string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
    if (String.IsNullOrEmpty(fullName))
    {
        throw new ArgumentException(MvcResources.Common_NullOrEmpty, "name");
    }

    bool usedViewData = false;

    // If we got a null selectList, try to use ViewData to get the list of items.
    if (selectList == null)
    {
        selectList = htmlHelper.GetSelectData(name);
        usedViewData = true;
    }
    ....etc
}

MVCSourceCode