User Name:

User Email:

This information will only be saved for the purposes of communicating with those who have provided this information voluntarily regarding our services.We will never sell your name or email address to anyone.
© 2021 - First Crazy Developer (Abhishek Kumar)

crazydeveloper How to pass javascript object into Web API

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.

public class Product
 public int Id { get; set; }
 public string Name { get; set; }
 public string Category { get; set; }
 public decimal Price { get; set; }
 interface IProductRepository
 Product Add(Product item);
 //To Do : Some Stuff
public class ProductRepository : IProductRepository
 private List products = new List();
 private int _nextId = 1;
 public ProductRepository()
 // Add products for the Demonstration
 Add(new Product { Name = "Computer", Category = "Electronics", Price = 23.54M });
 Add(new Product { Name = "Laptop", Category = "Electronics", Price = 33.75M });
 Add(new Product { Name = "iPhone4", Category = "Phone", Price = 16.99M });
 public Product Add(Product item)
 if (item == null)
 throw new ArgumentNullException("item");
 // TO DO : Code to save record into database
 item.Id = _nextId++;
 return item;
 //To Do : Some Stuff

View (Product.cshtml)



Add New Product











Web API Controller

public class ProductController : ApiController
 static readonly IProductRepository repository = new ProductRepository();
 public Product PostProduct(Product item)
 return repository.Add(item);

How it work ?

The same thing you have to done with MVC while calling MVC controller method using jQuery-JSON.

crazydeveloper Home Page 27 April 2015

Become a Fan