Dropdown无法保存:MVC C# 共享组合类数据如何保存到SQL Server另一张表
问题根源及修复方案
1. 核心错误原因
- 下拉框配置不匹配:你用
@Html.DropDownListFor生成的下拉框,SelectList指定的value字段是RowID,text字段才是Descriptions,所以表单提交时传的是选中项的RowID数值,不是描述文本,你直接取First_Table.Descriptions拿到的是ID值,自然不符合你存描述的需求。 - 手写拼接SQL存在严重SQL注入风险,一旦描述内容包含单引号会直接触发SQL语法错误,也是保存失败的常见诱因。
- 只要你的Model属性命名匹配,MVC会自动把表单提交的值绑定到入参的
tblSecond对象对应属性上,不需要手动从HttpContext.Request.Form取值。
2. 修复方案
方案1:直接存描述文本(调整下拉框配置即可)
把下拉框的value字段改为Descriptions,确保提交的就是描述文本:
<tr> <th colspan="6" > Product Description: <br /> </th> <th colspan="6"> @Html.DropDownListFor(m => m.First_Table.Descriptions, new SelectList(ViewBag.GetProducts, "Descriptions", "Descriptions"), "Please Select", new { @class = "form-control", @id= "ddlDescription" }) </th> </tr>
后端改用参数化查询,避免SQL注入和语法错误:
public ActionResult Index(tblSecond tblSecond) { // 直接从自动绑定的对象取值即可 string description = tblSecond.First_Table.Descriptions; using (SqlConnection connection = new SqlConnection(strSQLconnection)) { connection.Open(); // 用参数化查询替代字符串拼接 string sql = "insert into tbl_insertintosql(description) Values (@description)"; using (SqlCommand command = new SqlCommand(sql, connection)) { command.Parameters.AddWithValue("@description", description); command.ExecuteNonQuery(); connection.Close(); } } return RedirectToAction("Index"); }
方案2:保留RowID提交,查询后存描述(更符合关联表设计规范)
如果业务需要保留RowID做关联,不需要改前端代码,后端先通过提交的RowID查询到对应描述再插入即可:
public ActionResult Index(tblSecond tblSecond) { // 拿到提交的选中项RowID int selectedRowId = int.Parse(tblSecond.First_Table.Descriptions); // 用EF查询对应描述,示例中上下文名称为YourDbContext,可替换为你实际的EF上下文对象 string description = YourDbContext.Products.First(p => p.RowID == selectedRowId).Descriptions; // 后续参数化插入代码和方案1一致 }
内容的提问来源于stack exchange,提问作者fl13
相关产品推荐
相关产品推荐

