0

Current Code Example:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> ActionName(ViewModel model)
    { 
        if (!ModelState.IsValid)
        {
            return PartialView(model);
        }
        var result = //something
        if (result.Succeeded)
        {
            return PartialView(model);
        }
        AddErrors(result);
        return PartialView(model);
    }

Form Html

@model ViewModel

@using (Html.BeginForm("ChangePassword", "Manage", FormMethod.Post, new { @id = "Form"}))
{
   @Html.AntiForgeryToken()
   @Html.ValidationSummary("", new { @class = "text-danger" })

//Controls

<div class="form-group">
    <input type="submit" value="Save" data-loading-text="Loading..." class="btn btn-default" />
</div>
}

JQuery code Template:

    $("#Form").on('click', ".btn", function (e) {
    e.preventDefault();

    $.ajax({
        url: "Something/ActionName",
        //datatype: "text",
        data: $('#Form').serialize(),
        type: "POST",
        success: function (data) {                
            $("#Form").html(data);
        },
        error: function (result) {
            alert(result);
        }
    });
});

Now how can I know if an AJAX POST was a success and at the same time also returning the Partial View? Return PartialView to reset Form controls and clear error incase there were on the last post.

We can create a Json result with a var and RenderPartialView as string value. Please see MVC Return Partial View as JSON :

            if (data.Result == "Success") {
                alert("Data Saved");
            }
            $("#Form").html(data);

However, is there an easier option I am missing?

Community
  • 1
  • 1
Shyamal Parikh
  • 2,988
  • 4
  • 37
  • 78
  • Can you post your complete Form code? – Ala Aug 23 '15 at 13:07
  • Edited the question. – Shyamal Parikh Aug 23 '15 at 13:13
  • Your using ajax to post the form so there is no need to return the form again (its already in the view!). Just return json indicating success or otherwise, for example `return Json( new { result = "success");` - in which case you could just reset the form, or `return Json( new { result = "error", errormessage = "....");` - in which case you might display the error message –  Aug 23 '15 at 13:33
  • @StephenMuecke But if I don't return PartialView I would have to add Validation Errors to the Form manually right? – Shyamal Parikh Aug 23 '15 at 13:40
  • No, If you have included `ValidationSummary()` or `ValidationMessageFor()` and included the relevant jquery scripts then you can use a submit button, handle the forms `.submit()` event, test `$('form').valid()` (and `return false;` if it's not so that the submit is cancelled) - any error messages will automatically be added to the view and the form will not be submitted to the controller. –  Aug 23 '15 at 13:49
  • $('form').valid() doesn't work. Custom function? – Shyamal Parikh Aug 23 '15 at 13:56
  • .valid() doesn't work. Stepping through debugger it just moves inside if ($('form').valid()){ } even though there is a validation error – Shyamal Parikh Aug 23 '15 at 19:50
  • Ok finally was able to get .valid() to work by including the Jquery function mentioned in this link http://johnculviner.com/the-unobtrusive-libraries-client-validation-on-ajax-in-asp-net-mvc-3/#comment-32655 – Shyamal Parikh Aug 23 '15 at 20:22

0 Answers0