title: Why is this AJAX form not working in MVC5?
body: <p>I am building a contact form for the website which is used in an ASP.NET MVC 5 application (Razor engine) with .NET 4.5. The form displays correctly and also seems to validate properly, however the AJAX part does not work at all.</p>
  
  <p>The idea is that when the user presses SUBMIT and all validations are successful that the server is contacted via AJAX to send the email. During this time the page should display the "in progress" rotating icon we see with all AJAX things. When done the server returns a JSON response indicating whether it was successful or not and a message. This information is then displayed on the divResult when the process finishes. </p>
  
  <p>But as I said, when I press submit the progress animation is shown, the email is sent and rather than getting the JSON result in my DIV, the whole page is replaced by the raw JSON response. What am I missing here?</p>
  
  <p>My EmailModel is as follows (omitting validation attributes for brevity):</p>
  
  <pre><code>public class EmailModel {
      [Required]
      public string Subject { get; set; }
      [Required]
      public string FromEmail { get; set; }
      [Required]
      public string FromName { get; set; }
      [Required]
      public ItemViewModel Receptor { get; set; }
      [Required]
      public string MessageBody { get; set; }
  }
  </code></pre>
  
  <p>The "Receptor" is simply a construct whereby I show a list of tags in the contact form rather than the email address, for example "Info", "Feedback", etc. It is displayed in the view as a drop down list with the given "tags" and one of those is pre-selected.</p>
  
  <p>My ItemViewModel looks like this:</p>
  
  <pre><code>public class ItemViewModel {
      public string SelectedId { get; set; }
      public IEnumerable&lt;SelectListItem&gt; Items { get; set; }
  }
  </code></pre>
  
  <p>The controller view method is pretty simple, it just creates an EmailModel model instance and sets all the values. Then the controller method returns an ActionResult like this:</p>
  
  <pre><code>EmailModel model = new EmailModel() { ... properties set here ... }
  return view(model);
  </code></pre>
  
  <p>The view would invoke the following controller method (Post) which also works fine:</p>
  
  <pre><code>[HttpPost]
  public JsonResult SendContactMail(Models.EmailModel model) {
      ResponseModel response;
      try {
          if (ModelState.IsValid) {
               response = SendEmail(model);   // pretty obvious what it does and it works
          } else {
              response = new ResponseModel { Success = false, ResponseText = "hum..." };
          }
      } catch (Exception ex) {
           response = new ResponseModel { Success = false, ResponseText = ex.Message };
      }   
  }
  </code></pre>
  
  <p>Finally my Razor view looks like this more or less:</p>
  
  <pre><code>@model Models.EmailModel;
  @using System.Web.Mvc.Ajax;
  @{
      ViewBag.Title = "contact form";
      System.Web.Mvc.Ajax.AjaxOptions ajaxopts = new AjaxOptions() { 
      HttpMethod = "Post", InsertionMode = InsertionMode.Replace, UpdateTargetId = "divResult",
      OnBegin = "OnBegin", OnComplete = "OnComplete", OnSuccess = "OnSuccess", OnFailure = "OnFailure"
  };    
  
  @using (Ajax.BeginForm("SendContactMail", "Mail", null, ajaxopts, 
              new { @encType = "multipart/form-data", @id = "contactusform", 
                    @name = "contactusform" }))
  {
      @Html.AntiForgeryToken()
      @Html.ValidationSummary(true)
  
      &lt;div class="editor-label"&gt;
          @Html.LabelFor(model =&gt; model.Subject)
      &lt;/div&gt;
      &lt;div class="editor-field"&gt;
          @Html.EditorFor(model =&gt; model.Subject)
          @Html.ValidationMessageFor(model =&gt; model.Subject)
      &lt;/div&gt;
  
      &lt;div class="editor-label"&gt;
          @Html.LabelFor(model =&gt; model.FromEmail)
      &lt;/div&gt;
      &lt;div class="editor-field"&gt;
          @Html.EditorFor(model =&gt; model.FromEmail)
          @Html.ValidationMessageFor(model =&gt; model.FromEmail)
      &lt;/div&gt;
  
      &lt;div class="editor-label"&gt;
          @Html.LabelFor(model =&gt; model.FromName)
      &lt;/div&gt;
  
      &lt;div class="editor-field"&gt;
          @Html.EditorFor(model =&gt; model.FromName)
          @Html.ValidationMessageFor(model =&gt; model.FromName)
      &lt;/div&gt;
  
      &lt;div class="editor-label"&gt;
          @Html.LabelFor(model =&gt; model.Receptor)
      &lt;/div&gt;
      &lt;div class="editor-field"&gt;
          @Html.DropDownListFor(model =&gt; model.Receptor.SelectedId, Model.Receptor.Items, new { @class = "select1" })
          @Html.ValidationMessageFor(model =&gt; model.Receptor)
      &lt;/div&gt;
  
      &lt;div class="editor-label"&gt;
          @Html.LabelFor(model =&gt; model.MessageBody)
      &lt;/div&gt;
      &lt;div class="editor-field"&gt;
          @Html.EditorFor(model =&gt; model.MessageBody)
          @Html.ValidationMessageFor(model =&gt; model.MessageBody)
      &lt;/div&gt;
  
      &lt;p&gt;
          &lt;input type="submit" name="operation" id="process" value="Send" class="btn btn-info" /&gt;
      &lt;/p&gt;
      &lt;/fieldset&gt;
  
  &lt;div id="divProcessing" style="text-align: center;"&gt;
      &lt;img src="/Images/ajax-loader.gif" /&gt;&lt;br /&gt;
      &lt;p&gt;@Resources_Controller_Mail.Msg_SendingEmail&lt;/p&gt;
  &lt;/div&gt;
  &lt;div id="divMsg"&gt;&lt;/div&gt;
  &lt;div id="divResult"&gt;&lt;/div&gt;
  
  }  @* ajax.beginform *@
  
  @section Scripts {
      @Scripts.Render("~/bundles/jqueryval")
  
      &lt;script type="text/javascript"&gt;
  
          $(document).ready(function () {
              // Hide the "busy" Gif at load:
              $("#divProcessing").hide();
              $("#divMsg").hide();
  
              // Attach click handler to the submit button:
              $('#process').click(function () {
                  $('#contactusform').submit();
              });
  
              // Handle the form submit event, and make the Ajax request:
              $("#contactusform").on("submit", function (event) {
                  event.preventDefault();
  
                  // Show the "busy" Gif:
                  $("#divProcessing").show();
                  $("#divResult").empty();
                  var url = $(this).attr("action");
                  var formData = $(this).serialize();
                  $.ajax({
                      url: url,
                      type: "POST",
                      data: formData,
                      dataType: "json",
                      success: function (resp) {
  
                          // Hide the "busy" gif:
                          $("#divProcessing").hide();
  
                          // Do something useful with the data:
                          // var image = resp.Success ? "/Images/Yes.png" : "/Images/No.png";
                          //$("&lt;h3&gt;&lt;img src=\"" + image + "\"/&gt;&lt;/h3&gt;" + "&lt;p&gt;" + resp.ResponseText + "&lt;/p&gt;").appendTo("#divResult");
                          $("&lt;h3&gt;" + resp.Success + "&lt;/h3&gt;" + "&lt;p&gt;" + resp.ResponseText + "&lt;/p&gt;").appendTo("#divResult");
                      }
                  })
              });
          });
  
          function OnBegin() {
              $("#divMsg").append("Ajax Begins");
              $("#divMsg").show();
          }
          function OnComplete() {
              $("#divMsg").append("Ajax Complete");
              $("#divMsg").show();
          }
          function OnSuccess() {
              $("#divMsg").append("Success");
              $("#divMsg").show();
          }
          function OnFailure() {
              $("#divMsg").append("Failed");
              $("#divMsg").show();
          }
      &lt;/script&gt;
  }
  </code></pre>
  
  <p>Now before somebody asks... the layout inserts/renders the following in the view AFTER the HTML <em>form</em> tag closes and just BEFORE the script shown above that has the <em>.ready()</em> function:</p>
  
  <pre><code>    &lt;script src="/Scripts/jquery-1.10.2.js"&gt;&lt;/script&gt;
      &lt;script src="/Scripts/bootstrap.js"&gt;&lt;/script&gt;
      &lt;script src="/Scripts/respond.js"&gt;&lt;/script&gt;
      &lt;script src="/Scripts/jquery.validate.js"&gt;&lt;/script&gt;
      &lt;script src="/Scripts/jquery.validate.unobtrusive.js"&gt;&lt;/script&gt;
  </code></pre>
  
  <p>And these are inserted (thanks for that tip!) in the HEAD section as suggested. They come from the MicrosoftMvcAjax.Mvc5 NuGet package which places them in the ~/Scripts folder:</p>
  
  <pre><code>&lt;script type="text/javascript" src="/Scripts/MicrosoftAjax.js"&gt;&lt;/script&gt;
  &lt;script type="text/javascript" src="/Scripts/MicrosoftMvcAjax.js"&gt;&lt;/script&gt;
  </code></pre>
  
  <p>Thus summarizing...</p>
  
  <ul>
  <li>Why is there no AJAX progress activity on the view?</li>
  <li>Why the view behaves like a regular HTTP post (without ajax) on submit?</li>
  </ul>