0

I need save to string value from SelectListItem. How can I do this? My Controller:

[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();
}

View:

Departament
<div>
    @if (ViewBag.Depts != null)
    {
        @Html.DropDownListFor(model => model.Id_department, ViewBag.Depts as SelectList)
    }
</div>
Steffen Moritz
  • 7,277
  • 11
  • 36
  • 55
G3k0S
  • 37
  • 1
  • 11
  • Why not also make the text the value of the dropdown when it was populated. Or show where you assign the `ViewBag.Depts`. because you can still have the same value and text for a dropdown list, that way it will automatically be assigned to your model. – Bosco Jul 06 '19 at 10:20
  • public ActionResult AddingEmp() { SelectList depts = new SelectList(db.Departaments, "Id", "Name"); ViewBag.Depts = depts; return View(); } – G3k0S Jul 06 '19 at 10:25
  • this will do `public ActionResult AddingEmp() { SelectList depts = new SelectList(db.Departaments, "Name", "Name"); ViewBag.Depts = depts; return View(); }` make sure the `Departaments` parameter is a string field – Bosco Jul 06 '19 at 11:01
  • @Bosco, thx you!!! i dont up your reputation (( my rep is 3 )) – G3k0S Jul 06 '19 at 12:00

1 Answers1

0

they also helped me here -> How to get DropDownList SelectedValue in Controller in MVC

Controller:

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();
}

And 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>
Bosco
  • 1,536
  • 2
  • 13
  • 25
G3k0S
  • 37
  • 1
  • 11