MVC中的下拉列表

时间:2016-02-16 10:29:41

标签: asp.net-mvc asp.net-mvc-4 html.dropdownlistfor

我在绑定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();
    }

从上面的代码我无法显示数据来自数据库的下拉列表。 帮助我实现视图中的下拉列表。

1 个答案:

答案 0 :(得分:1)

public ActionResult Index(CommentDateLayer obj)
{
    DataSet ds = obj.bindddl();
    //ViewBag.fname = ds.Tables[0]; - I even can't imagine sense in this row
    var selectList = new List<SelectListItem>();
    foreach (System.Data.DataRow dr in ds.Tables[0].Rows)
    {
        //ViewBag.fname = new SelectList(items, "DeptID", "DeptName");   
        selectList.Add(new SelectListItem() { Text = dr.DeptName, Value = dr.DeptID });
    }
    ViewBag.fname = new SelectList(selectList, "DeptName", "DeptID");
    //ViewBag.fname = items; - can't imagine too, after fill by values
    return View();
}

PS。你的代码真的很“脏”。而且,它是恶意的。我强烈建议重新设计整个架构(真的要说,创建架构,因为它根本不存在),特别是db层(指向sql注入)