asp.net-mvcpartial-viewsajax.beginform

ASP.NET MVC form on a Partial View


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.


Solution

  • 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)) });
        }
    }