1

What I want to do: submit a form via ajax and return a partial view into an existing div in the page (without navigating away from the current page)

I learned that ajaxSubmit allows form submission without redirection to other pages.

So, I have got a form:

<form id="addForm" method="post" action="_SaveConcession" enctype="multipart/form-data">

The action _SaveConcession is a controller method:

public ActionResult _SaveConcession(parameters ...)
{
     return PartialView("Common/_PopUpSave");
}

which returns a partial view.

The script:

$('#addForm').submit(function (e) {
    e.preventDefault();
    ...
    if (formValid) {
        $(this).ajaxSubmit({
            type: 'POST',
            dataType: "html",
            complete: function (data) {
                $('#div-for-partial').html(data);
                $("#addConcessionWindow").data("kendoWindow").close();
            }
        });
    }
});

using ajaxSubmit, the behaviour isn't the expected: the contents of div-for-partial are cleaned and show nothing in it. If I use the traditional ajax, the div-for-partial is filled with the partial view returned in the controller method. Below is the ajax which works as expected.

$.ajax({
    type: 'POST',
    url: "/MD/_SaveConcession",
    data: { 'id': id },
    dataType: "html",
    complete: function (data) {
        $('#div-for-partial').html(data);
    }
});

However, this last approach doesn't suit me as the partial view is returned into a new page - that's why I'm trying to use ajaxSubmit.

chiapa
  • 4,362
  • 11
  • 66
  • 106
  • returned as a new page means you don't have a reference for unobtrusive ajax on your view. add that and it should be sorted out – Matt Bodily May 12 '15 at 17:01
  • Probably a stupid question since you already linked where you got the ajaxSubmit() function, but do you have the plugin library loaded in your view (as well as the core jquery library)? – Eckert May 12 '15 at 17:03
  • Hi. I don't got it. "the parcial view is returned into a new page". Can you explain me that? – Márcio Gonzalez May 12 '15 at 17:07
  • As per your title, you can use @Ajax.BeginForm() – Mahedi Sabuj May 12 '15 at 17:18
  • 1
    Your last code block - using `$.ajax({..` - does **not** display the partial view on a new page. Ajax calls stay on the same page and do not redirect. If that's what you think is happening then you have other code causing a redirect. how are you calling the `$.ajax()` function? –  May 12 '15 at 23:13
  • @MattBodily, I don't understand your suggestion. What do you mean by "add that"? – chiapa May 13 '15 at 08:13
  • @Eckert, yes, I have the library loaded and the `ajaxSubmit` works fine. – chiapa May 13 '15 at 08:14
  • @MárcioGonzalez, instead of being loaded on the same page into the target div `div-for-partial`, a new page is loaded and its full contents are the partial view – chiapa May 13 '15 at 08:15
  • @StephenMuecke, yes, you are right and I know that. I am trying to use the `ajaxSubmit` as all the form fields are sent into the controller. Using `$.ajax({..` I have to put all the input fields in the `data` of the ajax function (data: { 'id': id, 'code: code, etc' },), and they are a lot. Also, I have dozens of forms throughout the application and don't want to have a specific function for each page, each with the input collection in every form. – chiapa May 13 '15 at 08:19
  • If your want to serialize all the form values and post view ajax, then you just use `data: $('form').serialize(),` –  May 13 '15 at 08:24
  • @chiapa, Stephen Muecke's comment is right. Ajax never will redirect you to another page. The goal of ajax is exactly that. I'm working in a asp.net mvc project right now, and i'm using ajax in many parts of it. The only way you are being redirected is another code doing that. Your last code block NEVER will do that. – Márcio Gonzalez May 13 '15 at 11:45
  • Yes @MárcioGonzalez, I know that. That code block is called after click on submit button and so, without `e.preventDefault()` the redirect happened. I am also using ajax elsewhere and no problem, it's just submitting forms that's causing issues. Anyway, I found that Stephen's suggestion of using `$('form').serialize()` allows me to do what I want. – chiapa May 13 '15 at 11:50
  • @StephenMuecke, I used your suggestion of `$('form').serialize()` and I got what I intended, after blocking the default form submission with `e.preventDefault`. If you write that as an answer I will accept it, although I will also try Eckert's answer and see how it goes – chiapa May 13 '15 at 11:51
  • If you are posting using ajax, then your button should be `` and then `$('#save').click(function() { $.ajax(...` so you don't need to worry about cancelling events. –  May 13 '15 at 11:56
  • Ok. Eckert's answer is very nice too. Booth are right and will work fine. So, you have 2 good solutions. Good luck in coding. ;-) – Márcio Gonzalez May 13 '15 at 11:57
  • @StephenMuecke, there's a problem: in form with `input type="file"`, the file isn't sent to the controller. How to workaround this? **EDIT** Ok, I found the solution [here](http://hayageek.com/jquery-ajax-form-submit/) – chiapa May 13 '15 at 14:36
  • Then you need to use `FormData` - refer [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) - better than using the obsolete Ajax helpers –  May 13 '15 at 21:34

1 Answers1

2

You can use the MVC approach with the AJAX form helper

@using (Ajax.BeginForm("_SaveConsession", "MD", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "div-for-partial", OnSuccess = "postSuccess", OnFailure = "postFailed" }))
{
  // your form fields here
}

<script>
  function postSuccess() {
    // anything else that needs handled after successful post
  }

  function postFailed() {
    alert("Failed to submit");
  }
</script>

The ajaxOptions "InsertionMode" and "UpdateTargetId" work together to tell your view that the data being returned needs to be inserted into the specified target id.

Eckert
  • 690
  • 4
  • 9
  • Thank you, this works fine. I still use the regular HTML form without the Razor helper but this is very nice to know. Also, no `ajaxSubmit` was needed after all. – chiapa May 13 '15 at 13:11