我正在尝试将数据插入数据库表中。不幸的是,数据没有插入数据库中。
控制器:
public class UserController : Controller
{
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
using (SqlConnection sqlCon = new SqlConnection(connectionstring))
{
sqlCon.Open();
string query = "INSERT INTO Member (@ID, @Name, @City, @Address) " +
"VALUES (ID, Name, City, Address)";
SqlCommand sqlcmd = new SqlCommand(query, sqlCon);
//model get,set method does not access
sqlcmd.ExecuteNonQuery();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
存储库:
public class UserMasterRepository : IUserMasterRepository
{
private List<UserMaster> users = new List<UserMaster>();
private int _nextId = 1;
public UserMaster Add(UserMaster item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
item.ID = _nextId++;
users.Add(item);
return item;
}
}
IUserMasterRepository:
public interface IUserMasterRepository
{
IEnumerable<UserMaster> GetAll();
UserMaster Get(int id);
UserMaster Add(UserMaster item);
bool Update(UserMaster item);
bool Delete(int id);
}
如何解决此问题?
答案 0 :(得分:0)
我相信对于 SQL Server ,您的INSERT
语句是错误的-尝试以下操作:
string query = "INSERT INTO Member (ID, Name, City, Address) " +
"VALUES (@ID, @Name, @City, @Address)";
INSERT INTO
之后的列列表必须列出数据库表中定义的列名-并且这些列没有前导{{1} }。
另一方面,@
部分中的参数占位符就是-参数-,并且它们的名称必须以前导VALUES (...)
开头。
然后必须定义这些参数,并且必须在调用@
之前为其提供一个值:
.ExecuteNonQuery()
答案 1 :(得分:0)
如@marc_s所建议,您需要更改插入的内联查询,并且在插入值之前,需要从FormCollection
获取记录。
我假设您具有类似这样的视图模型。
public class VM
{
public int Id { get; set; }
public string Name { get; set; }
public string City{ get; set; }
public string Adderess{ get; set; }
}
使用操作方法从FormCollection对象检索输入值:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
using (SqlConnection sqlCon = new SqlConnection(connectionstring))
{
sqlCon.Open();
//model get,set method does not access
sqlcmd.Parameters.Add("@ID", SqlDbType.Int).Value = collection["ID"];
sqlcmd.Parameters.Add("@Name", SqlDbType.VarChar, 100).Value = collection["Name"];
sqlcmd.Parameters.Add("@City", SqlDbType.VarChar, 100).Value = collection["City"];
sqlcmd.Parameters.Add("@Address", SqlDbType.VarChar, 100).Value =collection["Address"];
///continue
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}