我想将值插入db。
我的模特是
public bool Create(string userName) {
_userNA = userName;
if (validate()) {
using (DatabaseCommaned cmd = new DatabaseCommaned()) {
cmd.CommandText = "INSERT INTO tUser(UNA, FNAID, MNAID, LNAID, Email, MobCountryCode, Mobile, ST, LN, ExpDT) VALUES(@una, @fnaid, @mnaid, @lnaid, @email, @mobCode, @mobile, @st, @ln, @exp)";
cmd.Parameters.AddWithValue("@una", userName);
....
_userID = cmd.ExecuteInsertAndGetID();
if (_userID > 0) {
copyPropertiesInternally();
Logs.LogEvent(LogEvent.UserCreated, userName);
ResetPassword();
return true;
}
else {
_userNA = string.Empty;
return false;
}
}
}
else
return false;
}
任何人都可以告诉控制器如何为上述模型编写
答案 0 :(得分:1)
不是100%肯定你在问什么,但我会采取行动:
public ActionResult Create(string UserName)
{
var model = new User();
var created = model.Create(UserName);
if(created)
return View();
else
return RedirectToAction("Index");
}
编辑以回应评论:
你说你有一个模特。看起来应该是这样的:
public class UserModel
{
public string UserName {get;set}
public string Email {get;set}
public string FirstName {get;set}
}
您的控制器操作应该是:
public ActionResult Create(UserModel model)
{
if (validate(model) {
var user = new User();
user.Create(model);
return View();
}
else
return RedirectToAction("Index");
}
您的数据库插入代码应为:
public void Create(UserModel model) {
_userNA = model.UserName;
using (DatabaseCommaned cmd = new DatabaseCommaned()) {
cmd.CommandText = "INSERT INTO tUser(UNA, FNAID, MNAID, LNAID, Email, MobCountryCode, Mobile, ST, LN, ExpDT) VALUES(@una, @fnaid, @mnaid, @lnaid, @email, @mobCode, @mobile, @st, @ln, @exp)";
cmd.Parameters.AddWithValue("@una", userName);
//....
_userID = cmd.ExecuteInsertAndGetID();
if (_userID > 0) {
copyPropertiesInternally();
Logs.LogEvent(LogEvent.UserCreated, userName);
ResetPassword();
return true;
}
else {
_userNA = string.Empty;
return false;
}
}
}
这只是您提供的信息的一部分。它希望能让你走上正确的道路。
答案 1 :(得分:1)
创建一个ViewModel类,例如CreateUserViewModel
public class CreateUserViewModel
{
//add properties reflecting the fields you want to capture in your HTML form
[Required]
public string UserName { get; set; }
//... etc
}
然后创建你的控制器
public ActionResult CreateUser(CreateUserViewModel model)
{
if(ModelState.IsValid)
{
string username = model.UserName;
//... etc
bool created = MyUserModelClass.Create(username, ...);
if(created)
Return RedirectToAction("Index");
else
return View(model); //return the form
}
else
{
return View(model); //return the form
}
}