Search code examples
c#asp.netasp.net-mvchtml.dropdownlistforviewdata

Not able to populate dropdownlistfor with viewdata


I am new to mvc. I need to use dropdownlist in my website which holds value as emp_id and text as user_id . The problem is that the table is another database and i need to insert the emp_id to my database on create() action of my control. I am able to list the values with dropdownlist but how can i insert value to my model.I had try a lot wit dropdoenlistfor but i can't find any output other than "NULL VALUE EXCEPTION "

view

@Html.DropDownList("SelectedItem", (IEnumerable<SelectListItem>)ViewData["employees"]) @* this works fine@*


  @Html.DropDownListFor(model => model.empid,new SelectList((IEnumerable<SelectListItem>)ViewData["employees"], "Value","Text", Model.empid), "Select Employee")

controller

public ActionResult Create()
        {
            BussinessLayer.Utils utobj = new BussinessLayer.Utils();
            ViewData["employees"] = utobj.getEmployees();
            return View();
        }

class

public List<SelectListItem> getEmployees()
        {
            DBSet DB = new DBSet();
            SqlCommand cmd = new SqlCommand("select EmpID,User_ID from User_M");
            DataTable dt = DB.SelectFrom("ipaddress","sqlserver", cmd);
            List<employee> emplist = new List<employee>();
            employee emp;
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    emp=new employee();
                    emp.empid = dt.Rows[i][0].ToString();
                    emp.User_ID = dt.Rows[i][1].ToString();
                    emplist.Add(emp);
                }
            }

            List<SelectListItem> items = new List<SelectListItem>();
            foreach (employee s in emplist) items.Add(new SelectListItem { Text = s.User_ID, Value =s.empid });
            return items;

        }

Solution

  • public class IndexPageModel
    {
       public int PersonId {get;set;}
    }
    
    [HttpGet]
    public ViewResult IndexPage()
    {
        ViewBag.PersonList = new List<Person>{ ... };
        return new View();
    }
    
    [HttpPost]
    public ActionResult IndexPage(IndexPageModel model)
    {
        model.PersonId // Got it!
    }
    

    View:

    @model IndexPageModel
    
    @using(Html.BeginForm(){
        @Html.DropDownListFor(model => model.PersonId,new SelectList((IEnumerable<SelectListItem>)ViewData["employees"])
        <input type=submit value="go" />
    })