2014-12-20 62 views
0

我是mvc的新手。我需要在我的網站中使用dropdownlist,它的值爲emp_id,文本爲user_id。問題是表是另一個數據庫,我需要將emp_id插入到我的控制的create()動作的數據庫中。我能列出與下拉列表中的值,但我怎麼可以插入值,我model.I不得不嘗試了很多機智dropdoenlistfor,但我不能找到比「空值EXCEPTION」無法使用viewdata填充下拉列表

視圖其他任何輸出

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


    @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; 

     } 
+0

觀點是強烈的典範「用戶」我需要爲EMPID賦值輸入您需要顯示每個「用戶」 –

+0

你的模型和'Create()'的POST方法。當ViewData [「employees」]'已經是'SelectList'時,爲什麼在視圖中創建一個新的'SelecList'? –

回答

-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" /> 
})