无法使用viewdata填充dropdownlistfor

时间:2014-12-20 11:26:25

标签: c# asp.net asp.net-mvc html.dropdownlistfor viewdata

我是mvc的新手。我需要在我的网站中使用dropdownlist,其值为emp_id,文本为user_id。问题是该表是另一个数据库,我需要在我的控件的create()操作上将emp_id插入我的数据库。我可以使用下拉列表列出值,但是如何将值插入到我的模型中。我已经尝试了很多机智dropdoenlistfor但我找不到任何输出而不是&#34; NULL VALUE EXCEPTION&#34; < / p>

视图

@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")

控制器

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

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;

        }

1 个答案:

答案 0 :(得分:-1)

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!
}

查看:

@model IndexPageModel

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