我正在使用MVC4视图页面,我试图通过单击按钮将数据从文本框插入到我的MS SQL数据库中。我努力做到这一点,我想这个问题是“con.open()”,但我不知道在哪里声明它。这里是我的代码:从文本框中插入数据到数据库asp.net MVC4
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage" %>
<script runat="server">
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["GreenEnergyConnectionString1"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into CUSTOMER values ('"+TextBox2.Text+"', '"+TextBox3.Text+"', '"+TextBox4.Text+"','"+TextBox5.Text+"','"+TextBox6.Text+"', '"+TextBox7.Text+"', '"+TextBox8.Text+"')",con);
cmd.ExecuteNonQuery();
con.Close();
TextBox8.Text = "";
TextBox7.Text = "";
TextBox6.Text = "";
TextBox5.Text = "";
TextBox4.Text = "";
TextBox3.Text = "";
TextBox2.Text = "";
}
而在我的web.config我宣布:
<add namespace="System.Data.SqlClient"/>
<add namespace="System.Configuration"/>
相信我,你可以用MVC做得更好吗? – ssilas777
我想你的意思是使用网页表单会容易得多吗?到目前为止,我只使用MVC的。我试图用一个web表单,但当我运行它时出现错误,我想我必须更新一些东西?怎么样?在哪里? –
这是一个等待发生的SQL注入攻击。 – 48klocs