首页 > 解决方案 > 如何将选定的下拉列表项保存到asp.net mvc中的数据库表

问题描述

我已经从另一个表绑定下拉列表。但是因为我正在做注册页面,所以我需要将选定的项目文本保存到我的注册表中。我对 ASP.net MVC 非常陌生,所以请帮助某人。谢谢

我正在提供我的下拉绑定代码,然后我不知道该怎么做。

在控制器中:

 public ActionResult Index()
        {
            employee_databaseEntities2 db = new employee_databaseEntities2();
            ViewBag.User_Demo = new SelectList(db.City_table, "cityid", "cityname");
            return View();
        }

鉴于:

@Html.DropDownList("User_Demo", "Select City") 

这个 HttpPost 索引代码是我在控制器中插入其他字段的代码:

[HttpPost]
        public ActionResult Index(ValidateClass vc)
        {            
            string query = "insert into userReg values('" + vc.username + "','" + vc.age + "','" + vc.email + "','" + vc.password + "','" + vc.repassword + "','" + vc.gender + "','" + vc.cityname + "')";
            SqlCommand cmd = new SqlCommand(query, con);
            con.Open();
            cmd.ExecuteNonQuery();
            ViewData["Message"] = "Inserted Successfully";
            con.Close();
            return View();
        }

在 vc.Cityname 中,我需要该下拉值。ValidateClass 是我的模型名称。

标签: asp.net-mvc

解决方案


欢迎来到堆栈溢出!
您的 html 元素的名称必须与您的模型类相同才能正确绑定。您应该在代码中更改User_Democityname

 public ActionResult Index()
        {
            employee_databaseEntities2 db = new employee_databaseEntities2();
            ViewBag.cityname = new SelectList(db.City_table, "cityid", "cityname");
            return View();
        }

你的html代码

 @Html.DropDownList("cityname", "Select City") 

请考虑使用ORM连接到您的数据库以防止 sql 注入攻击。


推荐阅读