-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网站,并通过教程进行工作并精简基础知识。 –