How to pass javascript complex object to ASP.NET Web Api and MVC
来源:互联网 发布:unity3d fbx模型 编辑:程序博客网 时间:2024/06/08 09:32
http://www.dotnet-tricks.com/Tutorial/webapi/WPNJ120413-How-to-pass-javascript-complex-object-to-ASP.NET-Web-Api-and-MVC.html
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.
- How to pass javascript complex object to ASP.NET Web Api and MVC
- How to enable pretty urls with Asp.Net MVC and IIS6
- HOW TO Set Up Multi-Server ASP.NET Web Applications and Web Services
- How to build Multi-Language Web Sites with ASP.NET 2.0 and VS.Net 2005
- How to build Multi-Language Web Sites with ASP.NET 2.0 and VS.Net 2005
- An Introduction to ASP.NET Web API
- Introduction to ASP.NET Web API
- How to achive the CRUD in ASP.NET MVC(VS2010)
- How to debug ASP.NET MVC using source code
- ASP.NET MVC - how to make users confirm the delete
- Asp.Net Mvc: Model Binding to Simple Types, Complex Types, Collections, Dictionaries, Etc
- How To Pass Arrays Between Visual Basic and C
- How To Debug an ASP.NET Web Application
- How to By Pass Proxy
- The Droid Chronicles – Web Services: Using kSOAP2 to Pass Complex Objects
- How to inherit an Object in JavaScript
- How to clone an object in JavaScript
- how to use javascript Object.defineProperty?
- LeetCode 27. Implement strStr() (KMP算法-模式串匹配)
- 虚拟键值表
- [leetcode] Unique Paths
- Android SQLite CHECK这个关键词始终不能用。
- Java设计模式之适配器模式(Adapter Pattern)
- How to pass javascript complex object to ASP.NET Web Api and MVC
- Hadoop MapReduce之ReduceTask任务执行(四):排序与合并
- Yet Another Coding Corner - the first one
- List vs Array:谁适合做java中泛型对象的容器?
- 黑马程序员_细说接口
- [LeetCode38]Count and Say
- windows sdk编程系列文章 ---- 利用镂空制作特效界面
- Java 常用类
- Overloading the << Operator for Your Own Classes