Question

Basic problem: We are currently busy developing a C# MVC3 web application, and after writing a CustomMembershipProvider and a custom RegisterModel, our Register form does not seem to be working. this error is pretty frustrating.

Here's what happens: Form is displayed, with register button at the bottom:

<input type="submit" value="Register" />

However, when you click the register-button, nothing happens. Here's the HttpPost method:

    [HttpPost]
    public ActionResult Register(RegisterModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            MembershipCreateStatus createStatus = ((CustomMembershipProvider)Membership.Provider).CreateUser(model);

            if (createStatus == MembershipCreateStatus.Success)
            {
                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                    && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                ModelState.AddModelError("","Something went wrong");
            }
        }

        // If we got this far, something failed, redisplay form

        return View(model);
    }

Any thoughts? Any help would be greatly appreciated.

edit: for your "viewing" amusement - here's the complete view

@model PMES.Models.RegisterModel

@{
ViewBag.Title = "Register";
}

<h2>Create a New Account</h2>
<p>
Use the form below to create a new account. 
</p>
<p>
Passwords are required to be a minimum of 
@Membership.MinRequiredPasswordLength          characters in length.
</p>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript">            </script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"    type="text/javascript"></script>

@using (Html.BeginForm()) {
@Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the    errors and try again.")
<div>
    <fieldset>
        <legend>Account Information</legend>

        <div class="editor-label">
            @Html.LabelFor(m => m.Email)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(m => m.Email)
            @Html.ValidationMessageFor(m => m.Email)
        </div>

        <div class="editor-label">
            @Html.LabelFor(m => m.Password)
        </div>
        <div class="editor-field">
            @Html.PasswordFor(m => m.Password)
            @Html.ValidationMessageFor(m => m.Password)
        </div>

        <div class="editor-label">
            @Html.LabelFor(m => m.ConfirmPassword)
        </div>
        <div class="editor-field">
            @Html.PasswordFor(m => m.ConfirmPassword)
            @Html.ValidationMessageFor(m => m.ConfirmPassword)
        </div>

        <div class="editor-label">
            @Html.LabelFor(m => m.Name)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(m => m.Name)
            @Html.ValidationMessageFor(m => m.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(m => m.FirstName)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(m => m.FirstName)
            @Html.ValidationMessageFor(m => m.FirstName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(m => m.Mobile)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(m => m.Mobile)
            @Html.ValidationMessageFor(m => m.Mobile)
        </div>
        <p>
            <input type="submit" value="Register" />
        </p>
    </fieldset>
</div>
}

For even more viewing pleasure:

namespace PMES.Controllers
{
public class AccountController : Controller
{
    private IUserRepository userRepository;
    //
    // GET: /Account/LogOn
    public AccountController()
    {
        ProjectManagementContext context = new ProjectManagementContext();
        this.userRepository = new UserRepository(context);
    }

    /*public AccountController(IUserRepository userRepository)
    {
        this.userRepository = userRepository;
    }*/

    public ActionResult LogOn()
    {
        return View();
    }

    //
    // POST: /Account/LogOn

    [HttpPost]
    public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            if (Membership.ValidateUser(model.Email, model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.Email, model.RememberMe);
                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                    && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
        }

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

    //
    // GET: /Account/LogOff

    public ActionResult LogOff()
    {
        FormsAuthentication.SignOut();

        return RedirectToAction("Index", "Home");
    }

    //
    // GET: /Account/Register

    public ActionResult Register()
    {
        return View();
    }

    //
    // POST: /Account/Register

    [HttpPost]
    public ActionResult Register(RegisterModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            MembershipCreateStatus createStatus = ((CustomMembershipProvider)Membership.Provider).CreateUser(model);

            if (createStatus == MembershipCreateStatus.Success)
            {
                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                    && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                ModelState.AddModelError("","Something went wrong");
            }
        }

        // If we got this far, something failed, redisplay form

        return View(model);
    }

    //
    // GET: /Account/ChangePassword

    [Authorize]
    public ActionResult ChangePassword()
    {
        return View();
    }

    //
    // POST: /Account/ChangePassword

    [Authorize]
    [HttpPost]
    public ActionResult ChangePassword(ChangePasswordModel model)
    {
        if (ModelState.IsValid)
        {

            // ChangePassword will throw an exception rather
            // than return false in certain failure scenarios.
            bool changePasswordSucceeded;
            try
            {
                MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
            }
            catch (Exception)
            {
                changePasswordSucceeded = false;
            }

            if (changePasswordSucceeded)
            {
                return RedirectToAction("ChangePasswordSuccess");
            }
            else
            {
                ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
            }
        }

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

    //
    // GET: /Account/ChangePasswordSuccess

    public ActionResult ChangePasswordSuccess()
    {
        return View();
    }

    public JsonResult checkEmail(String email)
    {
        var result = Membership.FindUsersByEmail(email).Count == 0;
        return Json(result, JsonRequestBehavior.AllowGet);
    }

    #region Status Codes
    private static string ErrorCodeToString(MembershipCreateStatus createStatus)
    {
        // See http://go.microsoft.com/fwlink/?LinkID=177550 for
        // a full list of status codes.
        switch (createStatus)
        {
            case MembershipCreateStatus.DuplicateUserName:
                return "User name already exists. Please enter a different user name.";

            case MembershipCreateStatus.DuplicateEmail:
                return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

            case MembershipCreateStatus.InvalidPassword:
                return "The password provided is invalid. Please enter a valid password value.";

            case MembershipCreateStatus.InvalidEmail:
                return "The e-mail address provided is invalid. Please check the value and try again.";

            case MembershipCreateStatus.InvalidAnswer:
                return "The password retrieval answer provided is invalid. Please check the value and try again.";

            case MembershipCreateStatus.InvalidQuestion:
                return "The password retrieval question provided is invalid. Please check the value and try again.";

            case MembershipCreateStatus.InvalidUserName:
                return "The user name provided is invalid. Please check the value and try again.";

            case MembershipCreateStatus.ProviderError:
                return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

            case MembershipCreateStatus.UserRejected:
                return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

            default:
                return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
        }
    }
    #endregion
}

}

Était-ce utile?

La solution

Depending on how you have everything setup you might have to explicity tell the form where to post (in your view):

Change this:

Html.BeginForm()

to:

Html.BeginForm("Register", "YourController")

Autres conseils

Have you changed your routes from the default settings? It may not be hitting the controller due to a routing issue?

Also, use the inspect element feature of firebug or chrome dev tools and make sure that the form action="/Account/Register" and that it is not doing something weird when it is building the form.

Sometimes weird things happen and it doesn't build the form correctly.

Also you can use the Network tab in chrome dev tools to see what gets posted to the server when you hit the submit button and you can see the server response.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top