0

How to pass SelectedItem from DropDownListFor to public ActionResult Index(IndexViewModel indexViewModel). After submit i have emp=null. What i should place instead of "Number" in IndexViewModel.ListOfEmployee = new SelectList(ListOfEmployee, "Number", "Name");

Controller:

public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        List<Employee> ListOfEmployee = new List<Employee>();
        ListOfEmployee.Add(new Employee { Name = "Jhon", Number = 1 });
        IndexViewModel IndexViewModel = new IndexViewModel();
        IndexViewModel.ListOfEmployee = new SelectList(ListOfEmployee, "Number", "Name");

        return View(IndexViewModel);
    }
    [HttpPost]
    public ActionResult Index(IndexViewModel indexViewModel)
    {
        return View();
    }

}

View:

@model MvcApplication3.Models.IndexViewModel
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
@using(@Html.BeginForm())
{ 
@Html.DropDownListFor(model=>model.emp ,Model.ListOfEmployee)

    <input type="submit" />
}

Model:

public class IndexViewModel
{
    public SelectList ListOfEmployee { get; set; }

    public Employee emp { get; set; }
}
2
  • 1
    Possible duplicate of How to get DropDownList SelectedValue in Controller in MVC4 Commented Apr 11, 2016 at 14:56
  • You cannot bind a <select> element to a complex obect (typeof Employee). You property emp need to be type int - public int emp { get; set; } Commented Apr 11, 2016 at 22:56

1 Answer 1

2

You should keep a simple value type property to store the selected dropdown option value.

public class IndexViewModel
{
    public SelectList ListOfEmployee { get; set; }    
    public int SelectedEmployeeId { get; set; }
}

and in your view

@Html.DropDownListFor(x=>x.SelectedEmployeeId, Model.ListOfEmployee)

and in your HttpPost action, access this SelectedEmployeeId property which will give you the number corresponding to the selected name. If you want the complete employee object, you should query the db again with the number(id)

[HttpPost]
public ActionResult Index(IndexViewModel model)
{
    var selectedNumber= model.SelectedEmployeeId; 
    return View();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.