HI WELCOME TO SIRIS

How to pass javascript complex object to ASP.NET Web Api and MVC

ASP.NET Web API is one of the most powerful recent addition to ASP.NET framework. Sometimes, you have to post a form data using jQuery-JSON to Web API or MVC method, which have so many input fields. Passing each and every input field data as a separate parameter is not good practice, even when you have a strongly typed-view. The best practice is, pass a complex type object for all the input fields to the server side to remove complexity.
In this article, I am going to explain you how can you pass complex types object to the Web API and MVC method to remove complexity at server side and make it simple and useful.

Model Classes

Suppose you have the following Product class and repository for product.
  1. public class Product
  2. {
  3. public int Id { get; set; }
  4. public string Name { get; set; }
  5. public string Category { get; set; }
  6. public decimal Price { get; set; }
  7. }
  8.  
  9. interface IProductRepository
  10. {
  11. Product Add(Product item);
  12. //To Do : Some Stuff
  13. }
  14.  
  15. public class ProductRepository : IProductRepository
  16. {
  17. private List<Product> products = new List<Product>();
  18. private int _nextId = 1;
  19.  
  20. public ProductRepository()
  21. {
  22. // Add products for the Demonstration
  23. Add(new Product { Name = "Computer", Category = "Electronics", Price = 23.54M });
  24. Add(new Product { Name = "Laptop", Category = "Electronics", Price = 33.75M });
  25. Add(new Product { Name = "iPhone4", Category = "Phone", Price = 16.99M });
  26. }
  27.  
  28. public Product Add(Product item)
  29. {
  30. if (item == null)
  31. {
  32. throw new ArgumentNullException("item");
  33. }
  34. // TO DO : Code to save record into database
  35. item.Id = _nextId++;
  36. products.Add(item);
  37.  
  38. return item;
  39. }
  40. //To Do : Some Stuff
  41. }

View (Product.cshtml)

  1. <script type="text/javascript">
  2. //Add New Item by Web API
  3. $("#Save").click(function () {
  4.  
  5. //Making complex type object
  6. var Product = {
  7. Id: "0",
  8. Name: $("#Name").val(),
  9. Price: $("#Price").val(),
  10. Category: $("#Category").val()
  11. };
  12. if (Product.Name != "" && Product.Price != "" && Product.Category != "") {
  13. //Convert javascript object to JSON object
  14. var DTO = JSON.stringify(Product);
  15. $.ajax({
  16. url: 'api/product', //calling Web API controller product
  17. cache: false,
  18. type: 'POST',
  19. contentType: 'application/json; charset=utf-8',
  20. data: DTO,
  21. dataType: "json",
  22. success: function (data) {
  23. alert('added');
  24. }
  25. }).fail(
  26. function (xhr, textStatus, err) {
  27. alert(err);
  28. });
  29.  
  30. }
  31. else {
  32. alert('Please Enter All the Values !!');
  33. }
  34.  
  35. });
  36.  
  37. </script>
  38. <div>
  39. <div>
  40. <h2>Add New Product</h2>
  41. </div>
  42. <div>
  43. <label for="name">Name</label>
  44. <input type="text" id="Name" title="Name" />
  45. </div>
  46.  
  47. <div>
  48. <label for="category">Category</label>
  49. <input type="text" id="Category" title="Category" />
  50. </div>
  51.  
  52. <div>
  53. <label for="price">Price</label>
  54. <input type="text" id="Price" title="Price" />
  55. </div>
  56. <br />
  57. <div>
  58. <button id="Save">Save</button>
  59. <button id="Reset">Reset</button>
  60. </div>
  61. </div>

Web API Controller

  1. public class ProductController : ApiController
  2. {
  3. static readonly IProductRepository repository = new ProductRepository();
  4. public Product PostProduct(Product item)
  5. {
  6. return repository.Add(item);
  7. }
  8. }

How it work ?


 



The same thing you have to done with MVC while calling MVC controller method using jQuery-JSON.
What do you think?
I hope you will enjoy the tips while playing with Asp.Net Web API and MVC. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.