Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6339201
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T19:36:14+00:00 2026-05-24T19:36:14+00:00

Most of the code I see online on MVC3 has very little code in

  • 0

Most of the code I see online on MVC3 has very little code in the controller, but I can’t seem to figure out how to make this code more streamlined.

Maybe if you take a look at it you can suggest improvements. If you need to see my UserModel class, let me know.

Here’s the code for the Account controller.

namespace WebUI.Controllers
{
    public class AccountController : Controller
    {
        public ActionResult Register()
        {
            UserModel model = new UserModel();         

            EFCityRepository cityRepo = new EFCityRepository();
            model.Cities = new List<SelectListItem>();
            foreach (var city in cityRepo.FindAllCities()) {
                model.Cities.Add(new SelectListItem { Text = city.Name, Value = city.CityId.ToString(), Selected = true });
            }

            EFGenderRepository genderRepo = new EFGenderRepository();
            model.Genders = new List<SelectListItem>();
            foreach (var gender in genderRepo.FindAllGenders()) {
                model.Genders.Add(new SelectListItem { Text = gender.Name, Value = gender.GenderId.ToString(), Selected = true });
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult Register(UserModel model) 
        {
            EFCityRepository cityRepo = new EFCityRepository();
            model.Cities = new List<SelectListItem>();
            foreach (var city in cityRepo.FindAllCities())
            {
                model.Cities.Add(new SelectListItem { Text = city.Name, Value = city.CityId.ToString(), Selected = true });
            }

            EFGenderRepository genderRepo = new EFGenderRepository();
            model.Genders = new List<SelectListItem>();
            foreach (var gender in genderRepo.FindAllGenders())
            {
                model.Genders.Add(new SelectListItem { Text = gender.Name, Value = gender.GenderId.ToString(), Selected = true });
            }

            if (ModelState.IsValid)
            {
                Domain.User user = new Domain.User();
                user.UserRoleId = 1;
                user.Nickname = model.Nickname;
                user.Name = model.Name;
                user.Lastname = model.Lastname;
                user.GenderId = model.GenderId;
                user.Address = model.Address;
                user.Email = model.Email;
                user.Telephone = model.Telephone;
                user.MobilePhone = model.MobilePhone;
                user.Carnet = model.Carnet;
                user.DateOfBirth = model.DateOfBirth;
                user.DateOfRegistry = DateTime.Now;
                user.LastDateLogin = DateTime.Now;
                user.IsActive = false;
                user.LanceCreditBalance = 5;
                user.LancesSpent = 0;
                user.Login = model.Login;
                user.Password = model.Password;
                user.EmailVerificationCode = "TempTokenString";
                user.CityId = model.CityId;

                EFUserRepository repo = new EFUserRepository();
                var result = repo.CreateUser(user);

                if (result == UserCreationResults.Ok)
                {
                    FormsAuthentication.SetAuthCookie(model.Nickname, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    switch (result)
                    {
                        case UserCreationResults.UsernameExists:
                            ModelState.AddModelError("", "El nombre de usuario ya esta siendo utilizado.");
                            break;
                        case UserCreationResults.EmailAlreadyExists:
                            ModelState.AddModelError("", "Ese correo ya esta en uso.");
                            break;
                        case UserCreationResults.NicknameAlreadyExists:
                            ModelState.AddModelError("", "El nickname ya esta siendo utilizado.");
                            break;
                        case UserCreationResults.UnknownError:
                            ModelState.AddModelError("", "Algo durante el registro. Por favor intente de nuevo.");
                            break;
                        default:
                            break;
                    }
                }

            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
    }
}

I’m using Entity Framework as my ORM, it generates a User class automatically for me. However, I made a User*Model* class so I could add data annotations for the views to use. Maybe this is the wrong idea?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T19:36:15+00:00Added an answer on May 24, 2026 at 7:36 pm

    I have many suggestions. For startes, read up about Dependancy Injection and Inversion of Control (DI and IoC). They will make all that boilerplate object instantiation a thing of the past.

    Next, convert those for-each list builders into Linq expressions. Much more succinct and more likely faster as well.

    Then, in your post handler, again do the same things there. In addition, get to know AutoMapper, which will automatically map your view to domain classes and make your life much easier.

    If you did those things, your code would be reduced by 2x, maybe even 3.

    EDIT:

    An example linq query, because I really don’t know the definition of your objects… would look something like this:

    model.Cities = cityRepo.FindAllCities().Select(city => new SelectListItem() { 
             Text = city.Name, Value = city.CityId.ToString()}).ToList();
    

    Notice how you don’t have to new up a new List, since that’s returned by the ToList() method. It is also using projection to select the items into a new SelectListItem.

    Basically, you could write your method like this, using Dependancy Injection, Linq, and AutoMapper (it looks longer because i had to break lines multiple times to fit the small viewing are of SO):

    namespace WebUI.Controllers
    {
        public class AccountController : Controller
        {
            private IGenderRepository _genderRepo;
            private ICityrRepository _cityRepo;
            private IUserRepository _userRepo;
    
            public AccountController(IGenderRepository gr, ICityRepository cr, 
                   IUserRepository ur)
            {
                _genderRepo = gr;
                _cityRepo = cr;
                _userRepo = ur;
            }
    
            public ActionResult Register()
            {
                UserModel model = new UserModel();         
    
                // Selected property is ignored by MVC on SelectListItems
                model.Cities = _cityRepo.FindAllCities().Select(city => 
                        new SelectListItem() { Text = city.Name, 
                             Value = city.CityId.ToString()}).ToList();
    
                model.Genders = _genderRepo.FindAllGenders().Select(gender => 
                        new SelectListItem() { Text = gender.Name, 
                             Value = gender.GenderId.ToString()}).ToList();
    
                return View(model);
            }
    
            [HttpPost]
            public ActionResult Register(UserModel model) 
            {
                model.Cities = _cityRepo.FindAllCities().Select(city => 
                        new SelectListItem() { Text = city.Name, 
                             Value = city.CityId.ToString()}).ToList();
    
                model.Genders = _genderRepo.FindAllGenders().Select(gender => 
                        new SelectListItem() { Text = gender.Name, 
                             Value = gender.GenderId.ToString()}).ToList();
    
                if (ModelState.IsValid)
                {
                    Domain.User user = Mapper.Map<Domain.User, Model>(model)
    
                    var result = _userRepo.CreateUser(user);
                    if (result == UserCreationResults.Ok) {
                        FormsAuthentication.SetAuthCookie(model.Nickname, false);
                        return RedirectToAction("Index", "Home");
                    } else {
                        ModelState.AddModelError("", GetErrorString(result));
                    }
                }
    
                // If we got this far, something failed, redisplay form
                return View(model);
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

In most of the videos, I see expert JQuery developers writing complete code for
I am trying to use SpinLock, but even this most basic code in a
Most of the code I've written in .NET to make REST calls have been
I've worked out most of the code and have several game classes. The one
in most code examples I see people doing this. import javax.swing.*; // for the
We have a setup where most code, before being promoted to full production, is
Most JavaScript code is also syntactically valid ActionScript 3.0 code. However, there are some
I use astyle to format my code most of the time, and I love
I've done most of my code in as3, working from either document class or
I have an application with most of the code written in javascript. I am

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.