asp.net-mvc - 如何将选定的下拉列表项保存到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 是我的模型名称。
解决方案
欢迎来到堆栈溢出!
您的 html 元素的名称必须与您的模型类相同才能正确绑定。您应该在代码中更改User_Demo
为cityname
。
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 注入攻击。
推荐阅读
- android - React-Native Element 在滚动时改变大小
- python - 谷歌云如何获得授权?
- azure - Invoke-AzureRmVMRunCommand 参数传递突然失败
- f# - 在 F# 中存储对局部变量的引用
- java - 如何在java中获取特定日期的UTC值
- sql - 根据字段的不同计数设置列
- python-3.x - 为什么基于 if 的测试和基于 lambda 的测试之间的返回值差异
- javascript - 如何向 javascript dragElement 添加约束
- html - 白色 X 出现在我拥有的所有浏览器的灰色框中,但 iPad 上的 Safari 除外。我犯了错误还是Safari?
- javascript - three.js - 从 Matrix4 获取 X、Y、Z 旋转值