Home > Software engineering >  What is the best way to move your code out of the controller and into a helper method class in .NET
What is the best way to move your code out of the controller and into a helper method class in .NET

Time:12-18

How can I move repeated code sections out of a controller into a Helper Method class instead of having to repeat the code in .NET Core? Please let me know if I need to provide more details.

I need to move any REPEATED CODE SECTIONS out of this controller so that I can call this method in every other controllers that require it

User controller:

using myApp.Data;
using myApp.Models;
using myApp.Models.ViewModels;
using myApp.Utilities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
    
namespace myApp.Controllers
{
    [Authorize]
    public class UserController : Controller
    {
        private readonly ApplicationDbContext db;
        private readonly UserManager<ApplicationUser> userManager;
  
        public UserController(  ApplicationDbContext db,
                        UserManager<ApplicationUser> userManager)
        {
            this.db = db;
            this.userManager = userManager;
        }
    
        [HttpGet]
        public async Task<IActionResult> UpdateUserDetails(UpdateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await userManager.FindByIdAsync(model.Id);

                if (user == null)
                {   
                    //Calling Repeated Code in this controller
                    return UserNotFound();
                }
                else
                {
                    user.FirstName = model.FirstName;
                    user.LastName = model.LastName;
                    user.UserName = model.UserName;
                    user.PhoneNumber = model.PhoneNumber;
                }

                var result = await userManager.UpdateAsync(user);

                if (result.Succeeded)
                {
                    //Calling Repeated Code in this controller
                    return UpdateSuccess();
                }

                AddErrors(result);
            }

            return View(model);
        }
            
        //REPEATED CODE SECTION BEGINS (Extracted out of UpdateUserDetails Controller)
        public IActionResult UserNotFound()
        {
            TempData[HelperStatic.ErrorMessage] = HelperStatic.userNotFoundMsg;
            return View(HelperStatic.notFoundView);
        }
        
        public IActionResult UpdateSuccess()
        {
            TempData[HelperStatic.SuccessMessage] = HelperStatic.recordUpdatedMsg;
            return RedirectToAction(nameof(Index));
        }

        //REPEATED CODE SECTION ENDS
   }
}

A static helper class is already present in the project which has only static constants.

Static helper class used in the above controller:

namespace myApp.Utilities
{
    public static class HelperStatic
    {
        // Messages
        public const string SuccessMessage = "Success";
        public const string ErrorMessage = "Error";
        public const string userNotFoundMsg = "User not found";
        public const string recordUpdatedMsg = "Record updated";

        // Views
        public const string notFoundView = "NotFound";
    }
}

I need a different HelperMethod class with reusable action methods. How do I achieve this?

CodePudding user response:

Instead of a helper class, create a controller base class and move all the utility methods into that.

public class BaseController : Controller
{
    public IActionResult UserNotFound()
    {
        TempData[HelperStatic.ErrorMessage] = HelperStatic.userNotFoundMsg;
        return View(HelperStatic.notFoundView);
    }

    public IActionResult UpdateSuccess()
    {
        TempData[HelperStatic.SuccessMessage] = HelperStatic.recordUpdatedMsg;
        return RedirectToAction(nameof(Index));
    }
}

And you can use it like this.

public class HomeController : BaseController
{
    public IActionResult Index()
    {
        UserNotFound();
        return View();
    }
}
  • Related