如何将选定的值从droplistdown保存到字符串值

时间:2019-07-06 10:16:02

标签: c# asp.net-mvc entity-framework-6

我需要从SelectListItem保存到字符串值。我怎样才能做到这一点? 我的控制器:

[HttpPost]
public ActionResult AddingEmp(Employee addingEmp)
{
    string valJ = "Junior SE";
    string valM = "Middle SE";
    SelectList depts = new SelectList(db.Departaments, "Name", "Name"); 

    SelectListItem selectedItem = /*??? How do i save selected value ???*/ depts.Where(x => x.Value == valJ).First();

    addingEmp.departament = selectedItem.Text; //here me need selected value...
    db.Employees.Add(addingEmp);
    db.SaveChanges();
    return View();
}

查看:

Departament
<div>
    @if (ViewBag.Depts != null)
    {
        @Html.DropDownListFor(model => model.Id_department, ViewBag.Depts as SelectList)
    }
</div>

1 个答案:

答案 0 :(得分:0)

他们也在这里帮助了我-> How to get DropDownList SelectedValue in Controller in MVC

控制器:

public ActionResult AddingEmp()
{
    SelectList depts = new SelectList(db.Departaments, "Depart_Name", "Depart_Name");
    ViewBag.Depts = depts;
    return View();
}
[HttpPost]
public ActionResult AddingEmp(Employee addingEmp, FormCollection form)
{
    addingEmp.departament = form["Depart_Name"].ToString();       
    db.Employees.Add(addingEmp);

    db.SaveChanges();
    return View();
}

并查看:

Departament
<div>
    @if (ViewBag.Depts != null)
    {
        @*@Html.DropDownList("Id", ViewBag.Depts as SelectList)*@
        @Html.DropDownList("Depart_Name"@*model => model.Id_department*@, ViewBag.Depts as SelectList)
        @*@Html.DropDownListFor(Model => Model.Id_Department, ViewBag.Depts as SelectList, "Id")*@
    }
</div>