Calling a register method from 2 or more controllers best practice

Posted by PussInBoots on Stack Overflow See other posts from Stack Overflow or by PussInBoots
Published on 2013-11-21T16:27:19Z Indexed on 2014/08/24 4:20 UTC
Read the original article Hit count: 152

I don't want to repeat myself. That is, I don't want the same code in two different controllers.

I always start from a default mvc5 web app project. That project has a Register ActionMethod in an AccountController:

    //
    // 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);
    }

Say I have a CampaignController and I want to register a user when he/she is on that page, fills out his/her username and pass and clicks the send form/submit button. What is the best thing to do in the ActionMethod of that form/controller?

Yes, I want to have the registerform in two or more places.

What is the best way to accomplish this in mvc 5?

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about asp.net-mvc-5