title: MVC4 - When Passing Complex model to the Controller using Ajax
body: <p>This is a Java Script function that is called when a user clicks add to basket, I am testing out my Ajax call before I put in all my logic to build the correct values form my form, (so hard coded for now.)</p>
  
  <pre><code>    function AddItem() {
  
      var myproduct = { Id: 1, Price: 17, ProductName:"product name" }
  
      var cartItem = { Quantity: 1, Product: myproduct };
  
  
      $.ajax({
          url: "/Cart/AddItem",
          type: 'post',
          data: cartItem,
          success: function (data) {
              if (data.IsSuccess) {
                  alert("test Hello Success");
              }
  
              alert("test HELLO Fail");
          },
          error: function (jqXHR, textStatus, errorThrown) {
              alert(errorThrown + "- Error");
          }
      });
  }
  </code></pre>
  
  <p>The problem is when testing this Java Script my strongly typed parameter inside my controller action only has some of the values set, 
  My controller action looks like this:</p>
  
  <pre><code>[HttpPost]
      public JsonResult AddItem(CartItem cartItem)
      {  
          cartItem.Cart = cartService.GetCartCurrent(this);
          cartService.SaveCartItem(cartItem);
  
         //bla bla bla
  
       }
  </code></pre>
  
  <p>The Cart Item definition looks like this:</p>
  
  <pre><code>[Serializable]
  public class CartItem
  {
      [Key]
      public int Id { get; set; }
      public virtual Product Product { get; set; }
      public virtual List&lt;SelectedProductOption&gt; SelectedProductOptions { get; set; }
      public virtual Cart Cart { get; set; }
      public int Quantity { get; set; }
  
  }
  </code></pre>
  
  <p>So when I set a break-point CartItem.Quaintity = 1 but CartItem.Product is NOT NULL but the values for Product.Id = 0 and Product.Price is 0.</p>
  
  <p>Why??</p>
  
  <p>How do you set the inner object of the complex model.</p>
  
  <p>Any ideas?</p>