C# ASP MVC 3:使用表单在数据库中记录

C# ASP MVC 3:使用表单在数据库中记录,c#,asp.net,sql-server,asp.net-mvc-3,visual-studio-2010,C#,Asp.net,Sql Server,Asp.net Mvc 3,Visual Studio 2010,我正在尝试使用C语言、Visual Studio 2010和SQL Server 2005数据开发一个应用程序ASP MVC 3。 我想在数据库中创建记录,但我不能,因为我输入的参数、、、被视为NULL(当我将光标放在Insert(matricule,…)语句中的参数上时,编辑器告诉我它们为NULL) 这是应用程序显示的错误: The INSERT statement is in conflict with the FOREIGN KEY constraint "FK_Users_Account

我正在尝试使用C语言、Visual Studio 2010和SQL Server 2005数据开发一个应用程序ASP MVC 3。 我想在数据库中创建记录,但我不能,因为我输入的参数、、、被视为NULL(当我将光标放在Insert(matricule,…)语句中的参数上时,编辑器告诉我它们为NULL)

这是应用程序显示的错误:

The INSERT statement is in conflict with the FOREIGN KEY constraint "FK_Users_Account". The conflict occurred in database "Range" table "dbo.Account", column 'Type_User'.
声明已终止

PS 当我更改此声明时:

SqlCommand cmd = new SqlCommand("Insert Into Users(Matricule, Nom_User,PassWord, Type_User )Values('"+Matricule+"','"+Nom_User+"','"+passWord+"','"+Type_User+"')", cn);
据此:

SqlCommand cmd = new SqlCommand("Insert Into Users(Matricule, Nom_User,PassWord, Type_User )Values('user2','anouar','anouar','Admin')", cn);
它是手动工作的,这意味着不需要将值放入表单中


感谢您的回答,我这样更改了代码,但始终存在相同的问题:

public int Insert(string Matricule, string Nom_User, string passWord, string Type_User, string ID_UF)
    {
        SqlConnection cn = new SqlConnection(@"Data Source = SWEET-DE396641E \ SQLEXPRESS; User Id = adminUser; Password = adminUser; Initial Catalog = Gamme");
        cn.Open();


        string sqlquery = ("Insert Into Users(Matricule, Nom_User,PassWord, Type_User, ID_UF )Values(@Matricule, @Nom_User, @passWord, @Type_User, @ID_UF)");
        SqlCommand cmd = new SqlCommand(sqlquery, cn);


        cmd.Parameters.AddWithValue("@Matricule", this.Matricule);
        cmd.Parameters.AddWithValue("@Nom_User", this.Nom_User);
        cmd.Parameters.AddWithValue("@passWord", this.passWord);
        cmd.Parameters.AddWithValue("@Type_User", this.Type_User);
        cmd.Parameters.AddWithValue("@ID_UF", this.ID_UF);
        return cmd.ExecuteNonQuery();
    }
这就是错误:
参数化查询“(@Matricule nvarchar(4000)、@user_name nvarchar(4000)、@passWord nv”需要参数@Club number尚未指定。

您可能会混淆数据库空值和c空值。请尝试为任何空值发送DBNull.Value

此外,我建议您使用参数化查询。它们使您的代码更易于阅读,并避免了严重的安全问题(即使这只是家庭作业,最好还是练习安全代码)

类似这样的东西(未测试,但概念在这里)


首先,正如Nomad101所建议的,您需要确保正在填充post字段,并且控制器方法上有[HttpPost]属性,并在代码中调试/单步执行以验证是否填充了值


其次,您创建查询的方式会让您面临黑客攻击。永远不要将您的参数连接到查询中。我注意到Brian在我键入时发布了正确方式的说明。此外,您还想了解我提到的数据访问对象设计模式。

您确定rm正在发布正确的值?添加断点,检查控制器中
类型用户
的值。要将
类型用户
值插入
用户
表,此值必须在
帐户
表中可用。
SqlCommand cmd = new SqlCommand("Insert Into Users(Matricule, Nom_User,PassWord, Type_User )Values(@Matricule, @Nom_User, @passWord, @Type_User)", cn);
cmd.Parameters.Add("@Matricule", Matricule ?? DBNull.Value);
cmd.Parameters.Add("@Nom_User", Nom_User?? DBNull.Value);
cmd.Parameters.Add("@PassWord", PassWord?? DBNull.Value);
cmd.Parameters.Add("@Type_User ", Type_User ?? DBNull.Value);