-1
我在綁定MVC中的下拉列表時遇到問題。我的代碼如下。MVC中的下拉列表
型號:
public class CommentDateLayer
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["BlogContext"].ToString());
public int AddEmplyee(Comment cmt)
{
string sql = "INSERT INTO [MVCTest].[dbo].[tblComment]([Name],[Email],[Message]) " +
" VALUES " +
" ('" + cmt.Name + "','" + cmt.Email + "','" + cmt.Message + "')";
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
public IEnumerable<SelectListItem> Department { get; set; }
public DataSet bindddl()
{
SqlCommand cmd = new SqlCommand("spGetAllRec", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
public class Comment
{
[Required]
public string Name { get; set; }
[Required]
public string Email { get; set; }
[Required]
[DataType(DataType.MultilineText)]
public string Message { get; set; }
public int DeptID { get; set; }
public int PostId { get; set; }
}
控制器:
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(FormCollection frm)
{
Comment c = new Comment();
c.Name = frm["Name"];
c.Email = frm["Email"];
c.Message = frm["Message"];
CommentDateLayer cmnt = new CommentDateLayer();
if (cmnt.AddEmplyee(c) == 1)
{
ViewBag.Status = "Submitted !";
}
return View();
}
public ActionResult Index(CommentDateLayer obj)
{
DataSet ds = obj.bindddl();
ViewBag.fname = ds.Tables[0];
List<SelectListItem> items = new List<SelectListItem>();
foreach (System.Data.DataRow dr in ViewBag.fname.Rows)
{
ViewBag.fname = new SelectList(items, "DeptID", "DeptName");
}
ViewBag.fname = items;
return View();
}
從上面的代碼我無法顯示其中數據來自數據庫中的下拉列表。 幫我實現視圖中的下拉列表。
你是不是在給予任何數據到'items'選擇列表的 – anand
您還沒有顯示你的觀點!你如何生成下拉列表? –
你的'foreach'循環在每次迭代時都會根據一個空集合創建一個新的'SelectList'。我強烈建議您轉到MVC網站,並通過教程進行工作並精簡基礎知識。 –