質問

I'm creating a site in MVC4, which is the first time I've use MVC in .NET, I've sussed out the logging in and registration. I have this scenario:

The website has Role 'A' and Role 'B', when a user hasn't registered before I want to direct them to the registration page, when they click on the Register section on their specific section, I direct them to the registration page. However I want the registration page to automatically define their role, based on which Registration button they clicked.

So a user clicks button 'A' when they register they will be assigned Role 'A', and when Agent 'B' registers they are automatically assigned Role 'B'. I want to avoid get variables to stop people overriding the selection.

役に立ちましたか?

解決

There are a lot of ways how you can implement it. For example:

add bool IsAgentA to your RegisterModel class in AccountModels.cs

public class RegisterModel
    {
        [Required]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        public string ConfirmPassword { get; set; }

        public bool IsAgentA {get; set;}
    }

Add radio buttons for IsAgentA in your Registration View (Yes - Agent A, No - Agent b). I will not write it here.

And after that modify your Register ActionResult in AccountController as follows:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
   if (ModelState.IsValid)
   {
                try
                {
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                    WebSecurity.Login(model.UserName, model.Password);

                    if (model.IsAgentA)
                    {
                    Roles.AddUserToRole(model.UserName, "Role A"); // user in role A 
                    }
                    else
                    {
                    Roles.AddUserToRole(model.UserName, "Role B"); // user in role B
                    }

                    return RedirectToAction("Index", "Home");
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            return View(model);
        }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top