title: Using AJAX to contact a method on server
body: <p>I want to use ajax/call a webmethod in the controller by clicking a button that is in a <code>BeginForm</code></p>
  
  <p>I have a submit button in a <code>Html.BeginForm</code>. Clicking this button will as we know, send the info from the model to the server. Here is the simplified code.</p>
  
  <pre><code>        @using (Html.BeginForm()) 
  
  
       {
             ...
                  &lt;div class="form-group"&gt;
                      @Html.LabelFor(model =&gt; model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
                      &lt;div class="col-md-10"&gt;
                          @Html.EditorFor(model =&gt; model.FirstName, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
                          @Html.ValidationMessageFor(model =&gt; model.FirstName, "Navn skal angives", new { @class = "text-danger" })
                      &lt;/div&gt;
                  &lt;/div&gt;
  ...
  
       &lt;div class="form-group"&gt;
                  &lt;div class="col-md-offset-2 col-md-10"&gt;
                      &lt;input type="submit" value="Tilføj" class="btn btn-default" id="submitBut" /&gt;
                  &lt;/div&gt;
              &lt;/div&gt;
      }
  </code></pre>
  
  <p>The corresponding Controller looks like this</p>
  
  <pre><code> [HttpPost]
      public ActionResult AttachCard(Card model, int MemberID)
      { ... }
  </code></pre>
  
  <p>I will need to add the annotation <code>[WebMethod]</code></p>
  
  <p>My issue is that I want to use JQuery Dialog to notify the client, when the card is added. For this I need a true or false value from the server. The dialog message will depend on this boolean value.</p>
  
  <p>I have written some AJAX code. This is not tested yet, as I'm stuck</p>
  
  <pre><code>    function attachCard(MemberID, action, controller) {
      var url = '/' + action + '/' + controller;
  
      $.ajax({
          type: "POST",
          url: url,
          data: $("form").serialize(),
          contentType: 'application/html; charset=utf-8',
          dataType: "html",
          success: function (status) {
              alert("Test from server: " + status);
          },
          error: function (msg) {
              alert("Error");
          }
      })
  }
  </code></pre>
  
  <p>I want this ajax function to run when the user clicks on the button that you see in my <code>Html.BeginForm</code>. But is this possible? If I add an onclick listener while it's in the <code>BeginForm</code>, then the webmethod will be called twice I think, and this will result in an exception. I am thinking about moving that button out of the <code>BeginForm</code>, and add an onclick event on the button. But then the rest of the info from the model (in the BeginForm) won't be submittet.
  How can I do this?</p>