Click here to Skip to main content
15,881,659 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
if i type "controler/action" data in url send corectly,but when want to send, data to api data data send zero to method parameter

var urll = 'https://localhost:44337/api/apiialbums/GetAlbum';  
 $.ajax({
                
                type: "post",               
                url: urll, error: function () { alert("errore") },
                data:{id:25,x:2},
                success: function (dataa) {
                    alert("okk");
}
})


my api class code:

[HttpPost]
        public async Task<ActionResult<Album>> GetAlbum(int id,int x)
        {
            var album = await _context.Albums.FindAsync(id);

            if (album == null)
            {
                return NotFound();
            }
            return album;    
        }


What I have tried:

i can send data in url and dont use data:{id:25,x:2} that
in this case id,x send corectly.

var urll = 'https://localhost:44337/api/apiialbums/GetAlbum?id=25&x=3';  
 $.ajax({
                
                type: "post",               
                url: urll, error: function () { alert("errore") },
              //  data:{id:25,x:2},
                success: function (dataa) {
                    alert("okk");
}
})


and in my ipa method use [httppost]
[HttpPost]
        public async Task<ActionResult<Album>> GetAlbum(int id,int x)
        {
            var album = await _context.Albums.FindAsync(id);

            if (album == null)
            {
                return NotFound();
            }
            return album;    
        }


how to use data:{id:25,x:2} instead of send data in url?
Posted
Updated 8-Sep-20 18:54pm
v2

Have a look at this for discussions about param binding with POST

Parameter Binding in Web API[^]

Easiest solution is to have a class that represents your params

C#
public class GetAlbumParams
{
    public int id { get; set; }
    public int x { get; set; }
}


Then change your method to use that

C#
public async Task<ActionResult<Album>> GetAlbum(GetAlbumParams albumParams)
 
Share this answer
 
i use [FromForm] for method parameter:
[HttpPost]
        public async Task<ActionResult<Album>> GetAlbum([FromForm] int id,[FromForm] int x)
        {
            var album = await _context.Albums.FindAsync(id);

            if (album == null)
            {
                return NotFound();
            }
            return album;    
        }

default is [FromQuery].the [FromQuery] Causes the parameter value to be read from the url, but [FromForm] causes the value to be read from data:{id:25,x:2} in ajax code
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900