所以我刚开始学习MVC,并想知道我是否应该在我的控制器中使用多个动作,或只是一个来实现一个简单的注册页面。
我应该做这样的事情(多重行动):
HTML(RegisterForm)
clickuid
控制器
<form action="CheckRegistration" method="post">
Username:
<input type="text" name="username"/>
<input type="submit" value="Login" />
</form>
或者这(单一行动):
HTML(注册)
public ActionResult RegisterForm()
{
return View();
}
public ActionResult CheckRegistration()
{
bool success = true;
// Create User Object and populate it with form data
User currentUser = new User();
currentUser.Username = Request.Form["username"].Trim().ToString();
// Validate Registration
// code
// Add user to database
// code
if (success)
{
return View("Login");
}else
{
return View("RegistrationSuccess");
}
}
控制器
<form action="Register" method="post">
Username:
<input type="text" name="username"/>
<input type="submit" value="Login" />
</form>
按照我想到的第一种方式,它有多个动作并将其分成多个步骤。
第二种方式使用一个动作,因此当第一次调用Register视图时,它不会将用户添加到数据库,因为验证失败并且只返回View()。
从专业角度来看哪种方式更好(更好),或者这两种方式都是不好的方式,并且有更好的方法。
答案 0 :(得分:1)
您应该有一个简单的视图并在帖子中登录。
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
答案 1 :(得分:0)
您可以在MVC
中使用同名方法。
1)声明第一个方法为 [HttpGet]
所以它将返回View和
2)将第二种方法声明为 [HttpPost]
[HttpGet]
public ActionResult RegisterForm()
{
return View();
}
[HttpPost]
public ActionResult RegisterForm()
{
bool success = true;
String otherData = ""
// Create User Object and populate it with form data
User currentUser = new User();
currentUser.Username = Request.Form["username"].Trim().ToString();
// Validate Registration
// code
// Add user to database
// code
if (success)
{
return RedirectToAction("RegisterSuccess");
}else
{
return View("RegisterForm");
}
}