简体   繁体   中英

Asp.net MVC5 Why won't Html.ValidationSummary(false) display exception errors?

I am trying to get user account management working in an asp.net mvc5 website I am building. New user creation is mostly working, but I am having a problem displaying errors when an exception is thrown during the creation of the user. The exception is caught/handled and an error message is added to the ModelState object in the Create() action of my AdminController, but the error is not displayed when when I return to the Create view.

Other types of user creation errors, that do not result in an exception being thrown, do display properly. As a side note, when the problem occurs, a "spinner" on my browser never stops, indicating that the post that initiated the create action never completed. If I click on a menu in the browser, I navigate to the new page and the spinner goes away.

The Create() errors that display properly and are not associated with an exception occur when:

var newUserCreateResult = UserManager.Create(newUser, password)

returns:

newUserCreateResult.Succeeded == false

The create() errors that are associated with an exception and do not display properly occur when:

await UserManager.SendEmailAsync(newUser.Id, "Reset Password", "Please confirm your account and reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");

throws an exception. I'm using an SmtpMailService and an exception is thrown when the email server cannot be reached, or the smtp account configuration is incorrect.

Some things I've tried:

  1. @Html.ValidationSummary(true)
  2. Manually creating the error list by iterating through the ModelState errors in the Create view. The debugger indicates the code executes, but it still doesn't display.

My Create() action:

        // PUT: /Admin/Create
    [Authorize(Roles = "Admin")]
    [HttpPost]
    [ValidateAntiForgeryToken]
    #region public ActionResult Create(CreateUserDTO createUserDTO)
    public async Task<ActionResult> Create(CreateUserDTO createUserDTO) {
        ApplicationUser newUser = null;
        try {
            if (createUserDTO == null) {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var Email = createUserDTO.Email.Trim();
            if (Email == "") {
                throw new Exception("No Email");
            }
            // Create user
            newUser = new ApplicationUser { UserName = Email, Email = Email };
            var password = Membership.GeneratePassword(8, 3) + "aaZZ09";
            var newUserCreateResult = UserManager.Create(newUser, password);

            if (newUserCreateResult.Succeeded == true) {
                UserManager.AddToRole(newUser.Id, createUserDTO.SelectedRole);
                string code = await UserManager.GeneratePasswordResetTokenAsync(newUser.Id);
                code = HttpUtility.UrlEncode(code);
                var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = newUser.Id, code = code }, protocol: Request.Url.Scheme);
                await UserManager.SendEmailAsync(newUser.Id, "Reset Password", "Please confirm your account and reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return Redirect("~/Admin");
            } else {
                // Html.ValidationSummary displays these errors correctly
                foreach (string msg in newUserCreateResult.Errors) {
                    ModelState.AddModelError(string.Empty, msg);
                }
            }
        } catch (Exception ex) {
            // Html.ValidationSummary DOESN NOT display these errors
            ModelState.AddModelError(string.Empty, ex.Message);
        }
        if (newUser != null) {
            UserManager.Delete(newUser);
        }
        createUserDTO.Roles = GetAllRolesAsSelectList();
        return View("Create", createUserDTO);
    }

My Create.cshtml view:

    @model Nissan.Models.CreateUserDTO
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("Create", "Admin", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) {
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        <h4>Create User</h4>
        <hr />
        @Html.ValidationSummary(false, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Email,
           htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email,
               new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "",
               new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Roles,
           htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.SelectedRole, (Model == null) ? null : Model.Roles);
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
                @Html.ActionLink("Cancel",
               "Index",
               null,
               new { @class = "btn btn-default" })
            </div>
        </div>
    </div>
}

This problem mysteriously disappeared (after I rebooted my PC?). It's now posting errors from the exception as it should.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM