我创建了一个新的MVC项目,并将插入函数设置为db.我的问题是,当我将模型输入db时,它会记录两次.尝试调试,但遗憾的是找不到错误.下面的代码中有没有遗漏?
public class DbCode
{
protected SqlConnection conn;
public bool Open(string Connection = "MyDb")
{
conn = new SqlConnection(@WebConfigurationManager.ConnectionStrings[Connection].ToString());
try
{
var b = true;
if (conn.State.ToString() != "Open")
{
conn.Open();
}
return b;
}
catch (SqlException ex)
{
return false;
}
}
public bool Close()
{
try
{
conn.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
public int ToInt(object s)
{
try
{
return Int32.Parse(s.ToString());
}
catch (Exception)
{
return 0;
}
}
public int DataInsert(string sql)
{
int LastID = 0;
string query = sql + ";SELECT @@Identity;";
try
{
if (conn.State.ToString() == "Open")
{
SqlCommand cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
LastID = this.ToInt(cmd.ExecuteScalar());
}
return this.ToInt(LastID);
}
catch
{
return 0;
}
}
}
public class StudentModel
{
[Required]
[StringLength(5)]
public string productname { get; set; }
[Required]
[StringLength(5)]
public string quantity { get; set; }
[Required]
[StringLength(5)]
public string price { get; set; }
}
调节器
public class StudentController : Controller
{
protected DbCode DB = new DbCode();
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveDataStudent(StudentModel student)
{
if (ModelState.IsValid)
{
DB.Open();
int i = DB.DataInsert("INSERT INTO tblproducts(productname,quantity,price) VALUES('" + student.productname + "','" + student.quantity + "','" + student.price + "')");
if (i > 0)
{
ModelState.AddModelError("Success", "Save Success");
}
else
{
ModelState.AddModelError("Error", "Save Error");
}
DB.Close();
}
return RedirectToAction("Index", "Student");
}
}
学生观
@model MVC5.Models.StudentModel
@{
ViewBag.Title = "Index";
}
@using (Html.BeginForm("SaveDataStudent", "Student", new { @id = "Form" }, FormMethod.Post))
{
@Html.ValidationSummary();
@Html.AntiForgeryToken();
@Html.LabelFor(m => m.productname);
@Html.TextBoxFor(m => m.productname);<br/>
@Html.LabelFor(m => m.quantity);
@Html.TextBoxFor(m => m.quantity);<br />
@Html.LabelFor(m => m.price);
@Html.TextBoxFor(m => m.price);<br />
<input type="submit" value="Save" name="Save" />
}
添加了webconfig中的连接字符串
问题在于以下几点:cmd.ExecuteNonQuery(); LastID = this.ToInt(cmd.ExecuteScalar());
您执行相同的命令两次,因此将2条记录插入到数据库中.
为了读取最后一个标识值,我将定义一个存储过程,它将数据插入表中,然后返回最后一个标识值.该方法描述于here.
顺便说一下,您的代码还存在另一个严重问题.您可以通过连接字符串来定义sql命令.其中一些字符串来自用户端.这意味着您的代码容易受到SQL注入攻击.相反,您应该使用参数(参见this或this).
我还建议不要使用像这一行中的魔术常量conn.State.ToString()==“Open”更好的方法是使用枚举成员:conn.State == ConnectionState.Open.
查看更多关于在C#中asp.net mvc / sql双重注册的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did69433