【发布时间】:2013-11-21 06:25:32
【问题描述】:
您好,我正在尝试将数据插入到由用户填写的数据库中。我正在使用 Visual Studio 2010 Asp.net mvc 2。但我收到错误
找不到资源。/Fillcustomer/customerdetail。但是服务器名、用户名和密码正确。请更正我的代码。
customer.cs
namespace displaycustomer.Models
{
public class customer
{
public int id { set; get; }
public string customercode { set; get; }
public int amount { set; get; }
public int Insert(int cid,string ccode, int amount)
{
string sqlconn = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
SqlConnection cn = new SqlConnection(sqlconn);
cn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO tblcus(C_Id, C_Code, Amount) " +
" VALUES('" + cid + "','" + ccode + "', '" + amount + "')", cn);
return cmd.ExecuteNonQuery();
}
}
}
customerdetailcontroller.cs
namespace displaycustomer.Controllers
{
public class customerdetailController : Controller
{
//
// GET: /customerdetail/
public ActionResult Index()
{
return View();
}
public ActionResult Fillcustomer()
{
return View();
}
[HttpPost]
public ActionResult insert()
{
customer cus = new customer();
int id = Convert.ToInt16(Request.Form["customerid"]);
string code = Request.Form["customercode"].ToString();
int amt = Convert.ToInt16(Request.Form["amount"]);
int _records = cus.Insert(id, code, amt);
if (_records > 0)
{
return RedirectToAction("customerdetail", "Fillcustomer");
}
else
{
ModelState.AddModelError("", "Can Not Insert");
}
return View(cus);
}
}
}
fillcustomer.aspx
<form method="post" action="insert">
<table>
<tr>
<td>Customer Id</td>
<td><input type="text" name="customerid" /></td>
</tr>
<tr>
<td>Customer Code</td>
<td><input type="text" name="customercode" /></td>
</tr>
<tr>
<td>Amount</td>
<td><input type="text" name="amount" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"/></td>
</tr>
</table>
</form>
web.config
<connectionStrings>
<add name="ConnString" connectionString="server=servername; Initial Catalog=sample; UID=user; pwd=123; Integrated Security=True;" providerName="System.Data.SqlClient" />
【问题讨论】:
-
错误?你得到什么错误
-
这意味着您连接到 sql 时出错.. conn 字符串可能是错误的...
-
如果你不使用sql参数,你的代码可能有一天会被Sql Injection :(
标签: c# asp.net database asp.net-mvc-2