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.

sada
  • 584
  • 2
  • 8
  • 25
  • Why not just use `$("#requestForm").empty();` to remove the form? And what is your current problem and objective? – Tetsuya Yamamoto Jan 29 '19 at 01: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. – sada Jan 29 '19 at 07: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. – Tetsuya Yamamoto Jan 29 '19 at 07: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? – sada Jan 29 '19 at 07:31

2 Answers2

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)) });
    }
}
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
  • 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 http://localhost:2537/favicon.ico („default-src”)), when I send the fixed data in the form and I submit it second times. – sada Jan 29 '19 at 10:21
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");
                           }
                        }});

                });
Hamzeh.Ebrahimi
  • 305
  • 1
  • 6
  • 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. – sada Jan 29 '19 at 07:02