0

Which parts should I change to make my form Ajax Based or JQuery Based. (Based on your recommendation between Ajax or JQuery) How the code will look after the changes?

Here's the code

    @using (Html.BeginForm("Contact", "Home", FormMethod.Post, new { name = "send-contact", 
      id = "contactform1", @class="validateform" }))
    {       
          @Html.AntiForgeryToken()
          if (!String.IsNullOrEmpty(@ViewBag.SendResultMessage)) 
           {                
               <text>
                  @section CustomScripts
                  {
                      <script type="text/javascript">
                          $("#myModal").Show({ ...});
                      </script>
                  }
               </text>
           } 
           @Html.TextBoxFor(m => m.Name)                                
           <div class="validation">@Html.ValidationMessageFor(m => m.Name)</div>
           <button class="b.." id="btnSubmit" type="submit">Submit message</button>
    }
</div>

As a note also here I want to show a "Modal Dialog" , If using Ajax what should be set as UpdateTargetId ?

any help is really appreciated.

LastBye
  • 1,143
  • 4
  • 19
  • 37

1 Answers1

1

I suppose you are talking about using Ajax.BeginForm or using JQuery to Ajaxify a form ? First method is not so recommended, as it's rather limited, the JQuery approach is more common and more flexible.

You just need to put a little bit of JQuery in a js script tag like so

    $(function () {
        $('#contactform1').submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    //Alert success or update data on page
                    //for example $('#myModal').html(result)
                },
                error: function (result, textStatus, lerror) {
                    //Alert for errors
                }
            });

            return false;
        });
    });

What is done here is hooking to the submit event of the form via JQuery, then using the ajax method of JQuery to do your submit and preventing the regular submit of the form via return false;, notice the usage of this.action, this.method that allows you to keep your Html.BeginForm untouched by taking the url and post method (GET or POST) directly from the form itself. More info on that here

Note that you will also have to change the action in the controller to return only some piece of html for your modal (using a display template works nicely for that), a json object could also work with the added bonus of extra information. Here is extract of a piece of my own code that return the html of a display template for a search feature, that should give you the logic of what you want to do

    /*Meant to be called by ajax*/
    [HttpPost]
    public ActionResult fetchInvoicesHistory(FormCollection input)
    {
        string Quarter = input["filQuarters"];

        var viewModels = InvoicePerQuarter(Quarter);

        return PartialView("DisplayTemplates/InvoiceTable",viewModels.ToList());
    }

If you want to try Ajax.BeginForm remember to put just the name of javascript function in the AjaxOption option (no parenthesis, no semicolon ) like so :

@using (Ajax.BeginForm(new AjaxOptions {
        HttpMethod = "POST",
        OnSuccess = "SaveSucces",
        OnFailure = "handleAjaxError"
}))
Community
  • 1
  • 1
Simon Rapilly
  • 393
  • 1
  • 13
  • I prefer the more recommended approach so the 2nd form (JQuery), thanks for the info, Now I'm reading, what about "the form's code" itself? should there be any changes also or not? Probably be the answer, +1 already for the participation – LastBye Aug 02 '13 at 12:14
  • Do you mean the **Html.beginform** ? This don't need to change for the code I gave you, the controller's action on which on the form point however, may have to change, ajax via JQuery support a number of types for the **result** parameter in the **success** function, in your case, since you want to show some data in a modal, I suggest returning from the action some html, via the **PartialView** method. I'll edit my answer on that – Simon Rapilly Aug 02 '13 at 12:26
  • Here added a bit of my own code, so you can see better what I mean – Simon Rapilly Aug 02 '13 at 12:31
  • Marked it as an answer, cause your posts will help me on this, I should play with it till make it work, You said return a partialView instead of the view, I want to show a "modal dialog" which you mentioned to place the running code below the "success" method. Am I right on these? Thanks for all your help – LastBye Aug 02 '13 at 12:37
  • Oh you can use `Person` as the type for the parameter, in my method I `FormCollection` because I didn't want to create an extra model just to receive a filter value, you will need however to change `return View (person)` because the `View` method is meant to generate a complete **HTML** page, where `PartialView` is meant to generate only, as the name imply, a bit of **HTML** – Simon Rapilly Aug 02 '13 at 12:39
  • Yes, look for display template for ASP .NET, make view model for what you want to show once you are done server side with the Ajax request, then make a partial view of the view model as a display template (that's just mean placing it in the display template folder), then return from action the partial view, that will generate only the **HTML** bits of the display template and in the jquery **success** method you will just have to do `$('#myModal').html(result)` to load the generated **html** inside your page (and then display it of course) – Simon Rapilly Aug 02 '13 at 12:44