Ajax.BeginForm and its onFailure and onSuccess methods

How to work with methods onFailure

and OnSuccess

. I am currently adding onFailure js method, but its execution fails. Maybe I forgot to add some scripts. (I only added jquery.unobtrusive.ajax.js

).

I need to return a partial view onFailure

to a modal window.

The code in the controller

  [HttpPost]
        public ActionResult RequestPassword(RequestForPasswordViewModel passwordRequestViewModel)
        {
             if (!ModelState.IsValid)
            {
               Response.StatusCode = (int)HttpStatusCode.BadRequest;
               return PartialView("RequestForPassword", passwordRequestViewModel);
            }

      

Partial code

@model YouCapital.Web.Models.ViewModels.RequestForPasswordViewModel

<div>

    @using (Ajax.BeginForm("RequestPassword", FormMethod.Post, new AjaxOptions()
    {
        InsertionMode = InsertionMode.Replace,
        HttpMethod = "POST",
        UpdateTargetId = "forgotPassword",
        OnFailure = "JsonRequestForPassword_OnFailure",
        OnSuccess = "JsonRequestForPassword_OnSuccess"

    }, new { @class = "form-inline" }))
    {



        <fieldset>
            <legend>Recover password</legend>
            <div class="form-group">
                @Html.Label("Enter your email")
                @Html.TextBoxFor(x => x.Email)
            </div>

            <input type="submit" class="btn btn-default" value="Recover"/>

        </fieldset>


         @Html.ValidationSummary()
    }




</div>


@section scripts
{
    <script>
        function JsonRequestForPassword_OnFailure() {
            console.log('fail');

        }
        function JsonRequestForPassword_OnSuccess() {
            console.log('success');
        }
    </script>
}

      

BTW I don't know if there is a problem, but it is in bootstrap modal

and howtabpanel

+3


source to share


1 answer


try these little things, add these scripts `

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

      

and in document.ready

 $(document).ready(function () {
    $.validator.unobtrusive.parse('#form');
});

      



and for the form

  @using (Ajax.BeginForm("Controller Method", "Controller Name", new AjaxOptions { HttpMethod = "POST",      OnSuccess = "JsonRequestForPassword_OnSuccess", UpdateTargetId = "forgotPassword" }, new { @id = "form" }))

      

Update target id must be whatever div or place owner your form has

+1


source







All Articles