title: Passing JavaScript object from jQuery AJAX to web method for custom serialization
body: <p>I have a problem in passing a JavaScript object to webmethod in asp.net.</p>
  
  <p>The JavaScript object is: </p>
  
  <pre><code>var Materials = new Object();
  function() {
              Materials.MaterialName = $('[id*="txtMaterialName"]').val();
              Materials.QuantityType = $('[id*="txtquantity"]').val();               
              AddNewMaterialToDb(Materials);
              $(this).dialog('close');
          }
  </code></pre>
  
  <p>Here materials is the object and now I want to pass it to a web method which takes a parameter of class type.</p>
  
  <p>Now I have two option:</p>
  
  <ol>
  <li>either to define the webmethod to take a parameter of MaterialEntity class which would automatically understand the JSON string passed from the AJAX method </li>
  <li>to create the webmethod to take the JSON string and serialize into MaterialEntity class</li>
  </ol>
  
  <p>How to do that when I am using jQuery AJAX? </p>
  
  <p>I mean to be specific how should I pass the jQuery object as data for jQuery AJAX so that any of the above two conditions gets satisfied?</p>
  
  <p>Function for jQuery AJAX: </p>
  
  <pre><code>function AddNewMaterialToDb(materials) {
  
  $.ajax({
      type: 'POST',
      contentType: "application/json; charset=utf-8",
      url: 'Services/Service.asmx/AddNewMaterial',      
      data :'{"Materials":"' + JSON.stringify(materials).replace('"', '\\\"') + '"}',
      dataType: "json",
      success: function(data, textStatus) {
          if (textStatus == "success") {
              if (data.d == true) {
                  alert('New Item Added');
              }
          }
      },
      error: function(data, textStatus) {
          alert('An error has occured retrieving data!');
      }
  });
  }
  </code></pre>