Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • David 29 posts 200 karma points
    Jan 13, 2021 @ 15:27
    David
    0

    Submitting From Ajax Form

    I have two problems when submitting from my Ajax login form.

    First problem is when i submit the login form without with the correct credentials all works fine, but if I input incorrect details there is any exception when trying to get the current pages id. (The form is a partial view)

    The other problem, is again when I input incorrect information, I would like it to return the reason why the user could not log in. For example no account exists with the specified email. But no messages are rendered on the screen when returning the partial. (hits the errors messages fine when debugging)

    Can anyone suggest or see what I am doing wrong in with these two issues? Any help in resolving this matter would be very much appreciated.

    Umbraco version: 8.6.1

    Here is my view/controller code:

    View

    @inherits UmbracoViewPage<CustomerLogin>
    @using QuoteBeater.Models.Membership;
    
    @{
        Model.PageSubmittedFromId = Umbraco.AssignedContentItem.Id;
    
        Html.EnableClientValidation();
        Html.EnableUnobtrusiveJavaScript();
    }
    
    <div id="ajaxLoginForm">
        @using (Ajax.BeginForm("Login", "AccountLogin", new { @id = "loginForm" }, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "ajaxLoginForm", OnSuccess = "onLoginSuccess" }))
        {
    
            MembershipViewData result = (MembershipViewData)TempData["LoginModel"];
    
            if (result != null && !result.Success)
            {
                <div class="alert alert-warning">
                    @if (result.Exception != null)
                    {
                        <div class="alert alert-danger">
                            <strong>Error:</strong> @result.Exception.Message
                        </div>
                    }
                    else
                    {
                        var message = result.Messages.Aggregate(string.Empty, (current, msg) => current + string.Format("<p>{0}</p>", msg));
    
                        <div>
                            @Html.Raw(message)
                        </div>
                    }
                </div>
            }
    
            @Html.AntiForgeryToken()
            <div class="form-group">
                @Html.LabelFor(x => x.Username)
                @Html.TextBoxFor(x => x.Username, new { @class = "form-control" })
                @Html.ValidationMessageFor(x => x.Username)
            </div>
            <div class="form-group">
                @Html.LabelFor(x => x.Password)
                @Html.PasswordFor(x => x.Password, new { @class = "form-control" })
                @Html.ValidationMessageFor(x => x.Password)
            </div>
            <div class="form-group ">
                @Html.HiddenFor(x => x.SuccessRedirectUrl)
                @Html.HiddenFor(x => x.PageSubmittedFromId)
                <input type="submit" value="Login" class="btn btn-primary pull-right" />
            </div>
        }
    </div>
    
    
    
    <script>
        var onLoginSuccess = function (result) {
            if (result.url) {
                window.location.href = result.url;
            }
        }
    </script>
    

    Controller (Surface Controller)

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Login(CustomerLogin model)
    {
        if (!ModelState.IsValid) return PartialView("~/Views/Partials/Forms/_LoginForm.cshtml", model);
    
        try
        {
            if (!Members.Login(model.Username, model.Password))
            {
                var member = Members.GetByUsername(model.Username);
                var viewData = new MembershipViewData { Success = false };
    
                if (member == null)
                {
                    viewData.Messages = new[] { "Account does not exist for this email address." };
                }
                else
                {
                    var messages = new List<string>
                {
                    "Login was unsuccessful with the email address and password entered."
                };
    
                    if (!member.Value<bool>("umbracoMemberApproved")) messages.Add("This account has not been approved.");
                    if (member.Value<bool>("umbracoMemberLockedOut")) messages.Add("This account has been locked due to too many unsuccessful login attempts.");
    
                    viewData.Messages = messages;
                }
    
                TempData["LoginModel"] = viewData;
                return PartialView("~/Views/Partials/Forms/_LoginForm.cshtml", model);
            }
            else
            {
    
                IPublishedContent currentPage = Umbraco.Content(model.PageSubmittedFromId);
    
                //If the Login Page else QuoteForm Page
                if (currentPage.IsDocumentType("accountLogin"))
                {
                    //https://stackoverflow.com/questions/9391201/ajax-beginform-that-can-redirect-to-a-new-page
                    return Json(new { url = "/account" });
                }
                else
                {
                    string currentPageUrl = Umbraco.Content(model.PageSubmittedFromId).Url(mode: UrlMode.Absolute);
                    return Json(new { url = currentPageUrl });
                }
            }
        }
        catch (Exception ex)
        {
            string exception = ex.Message;
        }
    
        return PartialView("~/Views/Partials/Forms/_LoginForm.cshtml", model);
    }
    
  • Huw Reddick 1737 posts 6098 karma points MVP c-trib
    Jan 13, 2021 @ 19:53
    Huw Reddick
    0

    Because you are using an ajaxform, you need to return a failure and process the result using an onfailure function, returning a view won't work the way you are expecting.

Please Sign in or register to post replies

Write your reply to:

Draft