我不想重复自己。也就是说,我不想在两个不同的控制器中使用相同的代码。
我总是从默认的mvc5网络应用程序项目开始。该项目在Register
:
AccountController
ActionMethod
//
// 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.UserName };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
假设我有一个CampaignController
并且我希望在他/她在该页面上时注册用户,填写他/她的用户名并通过并单击发送表单/提交按钮。在那个表单/控制器的ActionMethod中做的最好的事情是什么?
是的,我想在两个或更多地方注册。
在mvc 5中实现此目的的最佳方法是什么?
答案 0 :(得分:0)
创建逻辑层
将寄存器逻辑放在该逻辑层
中在网络图层中添加逻辑层作为参考
从两个动作结果中击中逻辑层中的函数:)
答案 1 :(得分:0)
至少在您的示例中...我会从您的广告系列视图中调用您的AccountController的操作。
答案 2 :(得分:0)
对我来说,在将当前的ControllerContext设置为AccountControllerContext
后,它就像一个魅力//This is employee controller class
public ActionResult Create([Bind(Include = "EmployeeId,FirstName,LastName,DOJ,DOB,Address,City,State,Mobile,Landline,ReportsTo,Salary")] Employee employee)
{
if (ModelState.IsValid)
{
AccountController accountController = new AccountController();
accountController.ControllerContext = this.ControllerContext;
//accountController.UserManager;
var userId = accountController.RegisterAccount(new RegisterViewModel { Email = "temp@temp.com", Password = "Pravallika!23" });
if (!string.IsNullOrEmpty(userId))
{
employee.UserId = userId;
employee.CreatedBy = User.Identity.GetUserId();
db.Employees.Add(employee);
db.SaveChanges();
return RedirectToAction("Index");
}
}
//customized method in AccountController
public string RegisterAccount(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
IdentityResult result = UserManager.Create(user, model.Password);
//to add roles
//UserManager.AddToRole(user.Id, "Admin");
if (result.Succeeded)
{
return user.Id;
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed
return null;
}