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

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

29 Mar 2024
Advanced
150K Views
7 min read

How to pass a javascript complex object to ASP.NET Web Api and MVC: An Overview

ASP.NET Web API is one of the most powerful recent additions to the ASP.NET framework. Sometimes, you have to post a form data using jQuery-JSON to Web API or MVC method, which has so many input fields.For both ASP.NET Web API and MVC, pass a JavaScript complex object using JSON.stringify() in the request body for better practice and reduced complexity, ensuring proper model binding on the server side.In this ASP .NET Web API Tutorial, I am going to explain to you how can you pass complex types of objects to the Web API and MVC method to remove complexity on the server side and make it simple and useful.

Pass a javascript complex object to ASP.NET Web Api and MVC

To pass on a JavaScript complex object to the ASP.NET Web API, use JSON.stringify() to convert it to a JSON string and deliver it in the request body. You may use the same way in ASP.NET MVC, or give the object as form data in a POST request. For all instances, provide adequate model binding and handling on the server side.

Model Classes

Suppose you have the following Product class and repository for a 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
}

This code defines a product blueprint (Product class) as well as an approach to organizing them in a collection (ProductRepository class). The Product class represents products and their attributes such as ID, name, category, and price. The ProductRepository class stores and handles products, issuing IDs and allowing new items to be added.

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>

This code generates a form for adding new products, collects user input, forwards it to a web API for processing, and displays success or error notifications.

Web API Controller

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

This code defines a controller for managing product-related API calls, to add new products using a specified repository.

Summary

Passing JavaScript complicated objects to ASP.NET Web API and MVC is simple: use JSON.stringify() to convert to JSON, then send in the request body. This approach benefits both systems by simplifying server-side handling and lowering complexity. Proper model binding ensures that data is transferred smoothly.

FAQs

Q1. How to pass multiple complex object data to Web API request?

Other than dynamic, JSON string, and custom class, tuple is the best approach to pass numerous complicated objects to Webapi services. When utilizing a tuple, there is no need to serialize and deserialize passing objects. Create an internal tuple object for the last tuple parameter if you want to communicate more than seven complicated objects.

Q2. How to pass complex objects to Web API?

One method is to pass the complex object as a [FromBody] attribute and the string argument as a Uri parameter, as demonstrated in the code snippet below. below. alert(data); }}); To parse the query string, you must edit your Web API controller method as shown below.

Q3. How to pass two parameters in URL?

To add a parameter to the URL, append a /#/? followed by the parameter name, an equal sign (=), and the parameter value. You can add additional parameters by separating them with an ampersand (&).

Q4. How to pass multiple values from controller to view in MVC?

ViewData is a class that is used to move data from the controller to the view. ViewData is a dictionary object that may be accessed through the use of a string as the key. We can pass any object from the controller to the view using ViewData. When enumerating in the view, the Type Conversion code is required.

Q5. Can I make API calls from JavaScript?

You can utilize the fetch API, which is built into modern browsers, to make API queries with JavaScript. It is a promise-based API that makes it simple to submit HTTP queries and respond to them asynchronously.
Share Article
Live Training Batches Schedule
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this