controller file

using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using WebApiService.Models; namespace WebApiService.Controllers { public class ProductController : ApiController { public IEnumerable<Product> Get() { Request.GetQueryNameValuePairs(); return new List<Product> { new Product(0,"Game",12.4f), new Product(1,"Yana",1f), new Product(2,"Maggy",56f), }; } public Product Post([FromBody]Product product) { // product = null return product;//don't work } } } 

Client application

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApiService.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script> </head> <body> <form id="form1" runat="server"> <div> </div> </form> <script> $(document).ready(function () { $.ajax({ url: "/api/product", type: "POST", data:{id:12,name:"Gomer",price:12}, contentType: "application/json", }).done(function (data) { alert(data); }).fail(function (err) { alert(err); }); }); </script> </body> </html> 

Wrong ajax wrote, are there any underwater stones?

    1 answer 1

    contentType you do not need to specify well, and as far as I remember the [FromBody] attribute is indicated only when it arrives from the form and not Json , but I can be wrong

     <script> $(document).ready(function () { var product = {id:12,name:"Gomer",price:12}; $.ajax({ url: '/api/product', type: 'POST', data:{product:product} }).success(function (data) { alert(data); }).error(function (err) { alert(err); }); }); </script> 
    • Anyway, the server receives null (Get works fine, it’s impossible to transfer data to the server for some reason. Constantly null or 0. Tried with [frombody] and without, still null ... damn. - WebWorkDeveloper
    • @WebWorkDeveloper tomorrow I can see what and how, today it is already too lazy to run the virtual user again. Tolerates? - Dmitry
    • @WebWorkDeveloper here look, decide your question c-sharpcorner.com/UploadFile/dacca2/… - Dmitry