0

I have page witha table and a button. When I push the button a partial view loads into a div. On the partial view there is an ajax form which sends back the partial view with validation error in case of wrong form data but I want to remove the partial view and refresh the table in case of successful insertion. The form header:

@using (Ajax.BeginForm("RequestInsert", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "requestForm" }, new { id = "reqins" }))

The jQuery submit event handler on the host page:

$(document).on('submit', '#reqins', function (e) { 
            e.preventDefault();  
            let data = $("form :input").serializeArray();
            $.ajax({
                url: '@Url.Action("RequestInsert", "Home")'
                ,type: "POST"
                ,data: { "__RequestVerificationToken": token, "model": data }
            })
                .done(function (data) {
                    $("#requestForm").html("");
                    table.search('').columns().search('').draw();
            })
            .fail(function (jqXHR, textStatus) {
                alert("fail");
            }); 
        });

I am a little confused with the partial view and ajax form.

4
  • Why not just use $("#requestForm").empty(); to remove the form? And what is your current problem and objective? Commented Jan 29, 2019 at 1:02
  • Thank you but my main problem how I can empty #requestForm div and in the same time refresh the table. The server side action sends back partial view and how can I decide in ajax success function whether it was a success and I can empty the requestForm or it was a failure and I must show the partial view again. Commented Jan 29, 2019 at 7:03
  • It depends on how you return the data from controller action. You can include a status response together with other data response, and use if-condition from there to call either empty() or simply redisplay partial view containing the form. Commented Jan 29, 2019 at 7:15
  • I return PartialResult so I must return a partial view but I do not send back any other flag about successfulness of the operation on the server. But maybe I can put a hidden tag into partial view form which can contain this flag? Commented Jan 29, 2019 at 7:31

2 Answers 2

1

Since your objective is checking validation status from AJAX response, you can use if condition against AJAX response as shown below:

$('#reqins').submit(function (e) {
    e.preventDefault();

    let data = $('form :input').serializeArray();

    $.ajax({
        url: '@Url.Action("RequestInsert", "Home")',
        type: 'POST',
        data: { "__RequestVerificationToken": token, "model": data },
        success: function (result) {
            // check valid response
            if (result.invalid) {
                $('#requestForm').html(result.form);
            }
            else {
                $('#requestForm').html(result);
                table.search('').columns().search('').draw();
            }
        },
        error: function (jqXHR, textStatus) {
            alert("fail");
        }
    });
});

Then inside controller action you can return both validation status and partial view using Controller.Json() with RenderViewToString() extension method provided here:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RequestInsert(ViewModel model)
{
    // perform validation here

    // assume IsValid is a boolean returned from validation status
    if (IsValid)
    {
        // successful validation, return empty form
        return PartialView("FormPartialView");
    }
    else
    {
        // validation failed, return failure status and previously-filled form
        return Json(new { invalid = true, form = RenderViewToString(PartialView("FormPartialView", model)) });
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I have ti change this a bit but it seems to me it begins to work but it throw an error (Content Security Policy: The page's settings blocked the loading of a resource at self localhost:2537/favicon.ico („default-src”)), when I send the fixed data in the form and I submit it second times.
0

try this and remove the Ajax Helper

$('#reqins').on('click', function () { 

            let data = $("form :input").serializeArray();

            $.ajax({
                url: '@Url.Action("RequestInsert", "Home")'
                ,type: "POST"
                ,data: data 
                ,success:function (result) {
                          $("#requestForm").html(result);
                        }});

                });

modify your action to this

public JsonResult RequestInsert()
        {
            try
            {
                return Json(new { success = true, result = PartialView("Prtialview") });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, result = ex.ErrorMessage });
            }
        }

and then modify the client side as following

$('#reqins').on('click', function () { 

            let data = $("form :input").serializeArray();

            $.ajax({
                url: '@Url.Action("RequestInsert", "Home")'
                ,type: "POST"
                ,data: data 
                ,success:function (result) {
                          if(result.succuss)
                          {
                             $("#requestForm").html(result);
                          }
                          else
                          {
                             alert("Error");
                           }
                        }});

                });

1 Comment

Thank you but my main problem how I can empty #requestForm div and in the same time refresh the table. The server side action sends back partial view and how can I decide in ajax success function whether it was a success and I can empty the requestForm or it was a failure and I must show the partial view again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.