控制器动作
本文关键字:控制器 | 更新日期: 2023-09-27 18:19:13
我想为db插入值。
my model is
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;
}
有谁知道上面模型的控制器是怎么写的吗
我不能百分百确定你在问什么,但我会试一试:
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;
}
}
}
这只是从你给出的零碎信息中得出的指导原则。希望它能让你走上正确的道路。
创建一个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
}
}