Please enable Javascript to correctly display the contents on Dot Net Tricks!

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

 Print 
  Author : Shailendra Chauhan
Posted On : 12 Apr 2013
Total Views : 105,788   
Updated On : 26 Sep 2016
 

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<Product> products = new List<Product>();
 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++;
 products.Add(item);

 return item;
 }
 //To Do : Some Stuff
}

View (Product.cshtml)

<script type="text/javascript">
//Add New Item by Web API
$("#Save").click(function () {

 //Making complex type object
 var Product = {
 Id: "0",
 Name: $("#Name").val(),
 Price: $("#Price").val(),
 Category: $("#Category").val()
 };
 
 if (Product.Name != "" && Product.Price != "" && Product.Category != "") {
 //Convert javascript object to JSON object
 var DTO = JSON.stringify(Product);
 $.ajax({
 url: 'api/product', //calling Web API controller product
 cache: false,
 type: 'POST',
 contentType: 'application/json; charset=utf-8',
 data: DTO,
 dataType: "json",
 success: function (data) {
 alert('added');
 }
 }).fail(
 function (xhr, textStatus, err) {
 alert(err);
 });

 }
 else {
 alert('Please Enter All the Values !!');
 }

});

</script> 
<div>
 <div>
 <h2>Add New Product</h2>
 </div>
 <div>
 <label for="name">Name</label>
 <input type="text" id="Name" title="Name" />
 </div>

 <div>
 <label for="category">Category</label>
 <input type="text" id="Category" title="Category" />
 </div>

 <div>
 <label for="price">Price</label>
 <input type="text" id="Price" title="Price" />
 </div>
 <br />
 <div>
 <button id="Save">Save</button>
 <button id="Reset">Reset</button>
 </div>
</div>

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.

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.



Free Interview Books
 
COMMENTS
imran Reply 291 days 8 hours 52 mins ago

Nice explain.

24 SEP
Angular2 and Angular4 (Classroom)
08:30 AM-11:30 AM IST
23 SEP
MEAN Stack (Classroom)
8:30 Am To 11:30 Am
23 SEP
Microsoft Azure Infrastructure Solutions (Online)
08:00 PM-11:00 PM IST / 9:30 AM-12:30 PM CST
20 SEP
MEAN Stack (Online)
07:00 AM-09:00 AM IST
20 SEP
ASP.NET MVC with Angular4 (Online)
9:00PM- 11:00PM IST(+5:30GMT)
16 SEP
Angular2 and Angular4 (Online)
08:00 AM-10:00 AM IST(+5.30 GMT)
7 SEP
ASP.NET MVC with Angular4 (Online)
09:00 PM to 11:00 PM IST (+5:30 GMT)
22 AUG
ASP.NET Core with Angular4 (Online)
07:00 AM - 9:00 AM IST(+5:30 GMT)
19 AUG
MEAN Stack 2 (Online)
5:30 Pm - 7:00 PM IST (+5:30 GMT)
19 AUG
ASP.NET MVC with Angular4 (Online)
10:30 Am to 12:30 PM IST (+ 5:30 GMT)
19 AUG
NodeJS with Angular4 (Classroom)
04:00 PM to 07:00 PM IST (+5:30 GMT)
12 AUG
ASP.NET MVC with Angular4 (Classroom)
11:30 AM - 1:30 PM IST (+5:30GMT)
15 JUL
ASP.NET MVC with Angular4 (Online)
03:30 PM - 05:30 PM IST(+5.30 GMT)
LIKE US ON FACEBOOK
 
+