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. publicclassProduct
  2. {
  3. publicintId{ 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. ProductAdd(Product item);
  12. //To Do : Some Stuff
  13. }
  14.  
  15. publicclassProductRepository:IProductRepository
  16. {
  17. privateList<Product> products =newList<Product>();
  18. privateint _nextId =1;
  19.  
  20. publicProductRepository()
  21. {
  22. // Add products for the Demonstration
  23. Add(newProduct{Name=“Computer”,Category=“Electronics”,Price=23.54M});
  24. Add(newProduct{Name=“Laptop”,Category=“Electronics”,Price=33.75M});
  25. Add(newProduct{Name=“iPhone4”,Category=“Phone”,Price=16.99M});
  26. }
  27.  
  28. publicProductAdd(Product item)
  29. {
  30. if(item == null)
  31. {
  32. thrownewArgumentNullException(“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. <scripttype=“text/javascript”>
  2. //Add New Item by Web API
  3. $(“#Save”).click(function(){
  4.  
  5. //Making complex type object
  6. varProduct={
  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. <labelfor=“name”>Name</label>
  44. <inputtype=“text”id=“Name”title=“Name”/>
  45. </div>
  46.  
  47. <div>
  48. <labelfor=“category”>Category</label>
  49. <inputtype=“text”id=“Category”title=“Category”/>
  50. </div>
  51.  
  52. <div>
  53. <labelfor=“price”>Price</label>
  54. <inputtype=“text”id=“Price”title=“Price”/>
  55. </div>
  56. <br/>
  57. <div>
  58. <buttonid=“Save”>Save</button>
  59. <buttonid=“Reset”>Reset</button>
  60. </div>
  61. </div>

Web API Controller

  1. publicclassProductController:ApiController
  2. {
  3. static readonly IProductRepository repository =newProductRepository();
  4. publicProductPostProduct(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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: