我是MVC 3的新手。我正在尝试在模型层插入数据,但它不会插入任何数据。 ExecuteNonQuery:Connection属性尚未初始化。 并且在调试过程中,ConnectDb方法的Constr参数接受连接字符串但不能在函数体中使用,返回null。我也试过了web.config。
CODE:
查看:
@using (Html.BeginForm("register","Home", FormMethod.Post, new {id="submitForm"}))
{
<div>
<i>@Html.Label("Name:")</i>
@Html.TextBox("txtboxName")
</div>
<div>
<i>@Html.Label("Email:")</i>
@Html.TextBox("txtboxEmail")
</div>
<div>
<i>@Html.Label("Password:")</i>
@Html.Password("txtboxPassword")
</div>
<div>
<button type="submit" id="btnSubmit" name="Command" value="Submit">Submit</button>
</div>
}
控制器:
namespace LoginSys.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Registration";
return View();
}
[HttpPost]
public ActionResult register(string command, FormCollection formData )
{
if (command == "Submit")
{
var name = formData["txtboxName"];
var email = formData["txtboxEmail"];
var pwd = formData["txtboxPassword"];
String conStr = "Data Source=HUNAIN-PC;Initial Catalog=registration;User ID=sa;Password=abc123!@#";
database db = new database();
db.connectDB(name, email, pwd, conStr);
ViewBag.Message = conStr;
}
return View();
}
}
}
模型:
public ConnectionStatus connectDB(String name, String email, String pwd, String conStr)
{
var con = conStr;
SqlConnection sqlCon = new SqlConnection(con);
SqlCommand sqlCom =new SqlCommand(con);
// sqlCom.Connection = sqlCon;
sqlCom.CommandText = "insert into tblRegister (Name, Email, Pwd) values (@name, @email, @pwd)";
sqlCom.Parameters.AddWithValue("@name", name);
sqlCom.Parameters.AddWithValue("@email", email);
sqlCom.Parameters.AddWithValue("@pwd", pwd);
ConnectionStatus connectStatus = new ConnectionStatus();
int row_aff;
try
{
sqlCon.Open();
row_aff = sqlCom.ExecuteNonQuery();
connectStatus.Message = "OK";
}
catch(Exception ex)
{
connectStatus.Message = ex.Message;
}
finally
{
sqlCon.Close();
}
return connectStatus;
错误: ExecuteNonQuery:连接属性尚未初始化。
我在调试过程中发现一个问题,我的方法COnnectDb接受ConnectionString作为'Constr'中的参数但是它不能在函数体中分配或使用,即var con = conStr;
为空,而我使用Constr参数的每个其他变量都是NULL,为什么?
![enter image description here][1]
答案 0 :(得分:0)
首先,你需要追踪自己的错误是什么,这是太多的可能性。
对于错误处理,有很多方法可以做到这一点,您可以在本文中看到:Error Handling
答案 1 :(得分:0)
1)为什么不将数据插入tbl?
因为您从未初始化命令的SqlConnection:
SqlConnection sqlCon = new SqlConnection(con);
SqlCommand sqlCom =new SqlCommand(con);
此处的sqlCon
变量与命令无关。初始化命令的正确方法是:
SqlConnection sqlCon = new SqlConnection(con);
SqlCommand sqlCom = sqlCon.CreateCommand();
这是在下面阅读的,以获得设计此方法的正确方法的完整示例。
2)catch(Exception ex){//如何将ex.message或错误返回给VIEW? }
您可以使用connectDB
方法(erm connectDB
来插入???)将潜在错误返回为out
参数。还要将这些IDisposable资源包装在using
语句中,否则您可能会非常糟糕地泄漏资源:
public bool TryInsertUser(string name, string email, string pwd, string conStr, out string error)
{
error = null;
using (var sqlCon = new SqlConnection(conStr)
using (var sqlCom = sqlCon.CreateCommand())
{
sqlCon.Open();
sqlCom.CommandText = "insert into tblRegister (Name, Email, Pwd) values (@name, @email, @pwd)";
sqlCom.Parameters.AddWithValue("@name", name);
sqlCom.Parameters.AddWithValue("@email", email);
sqlCom.Parameters.AddWithValue("@pwd", pwd);
try
{
sqlCom.ExecuteNonQuery();
return true;
}
catch(Exception ex)
{
error = ex.Message;
return false;
}
}
}
然后编写一个视图模型:
public class RegisterViewModel
{
public string Command { get; set; }
public string TxtboxName { get; set; } // <-- Find better name
public string TxtboxEmail { get; set; } // <-- Find better name
public string TxtboxPassword { get; set; } // <-- Find better name
}
您的控制器操作将作为参数:
[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
if (model.Command == "Submit")
{
// TODO: This usually goes into your web.config
string conStr = "Data Source=HUNAIN-PC;Initial Catalog=registration;User ID=sa;Password=abc123!@#";
database db = new database();
string error;
if (!db.TryInsertUser(model.TxtboxName, model.TxtboxEmail, model.TxtboxPassword, conStr, out error))
{
// Some error occurred while attempting to insert the record
// in the database -> we are adding this error to the ModelState
// so that it can be displayed in the view
ModelState.AddModelError("", error);
}
}
return View();
}
然后在您的视图中,您可以使用Html.ValidationSummary()
帮助程序显示潜在的错误消息。