【问题标题】:Dropdown is not saving - MVC C# Sharing a combined class and save into another table下拉不保存 - MVC C# 共享一个组合类并保存到另一个表中
【发布时间】:2021-12-10 20:36:13
【问题描述】:

我想知道如何保存以下内容。

我正在使用来自 EF 中多个类的信息填充文本字段和下拉列表,但不确定如何将信息保存到 SQL Server 中的另一个表中。

这是一个例子:

<tr>
    <th colspan="6" >
    Product Description: <br />
    </th>
    <th colspan="6">                                                          
    @Html.DropDownListFor(m => m.First_Table.Descriptions, new SelectList(ViewBag.GetProducts, "RowID", "Descriptions"), "Please Select", new { @class = "form-control", @id= "ddlDescription" }) 
    </th>
</tr>

上面的部分在页面加载时从查询中获取产品描述。

现在我想像这样将它保存到这个表中:

public ActionResult Index(tblSecond tblSecond)
{         
    string description = HttpContext.Request.Form["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.CommandType = CommandType.Text;
            command.ExecuteNonQuery();
            connection.Close();
        }
    }

    return RedirectToAction("");
}

我觉得这段代码是问题所在:

string description = HttpContext.Request.Form["First_Table.Descriptions"];

【问题讨论】:

  • 警告:您的代码危险;它对 SQL 注入攻击很开放。您需要尽快解决代码中的这个巨大安全漏洞。现在是 2021 年,没有理由不从其他人在过去几十年中犯下的错误中吸取教训。
  • 你是如何提交你的观点的?你能发布整个视图代码吗?

标签: c# sql-server asp.net-mvc


【解决方案1】:

对于任何想要答案的人:

您可以像这样创建一个模型对象并将其调用到您的字符串中,如下所示。

    public ActionResult Index(tblCombined model)
    {
              string descriptions = model.First_Table.Descriptions;
     }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    • 2010-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多