I am using ASP.NET WebApi 2.0 I have published it on localserver and am trying to consume the services
This is how my Api Controller looks
public class TestController : ApiController
{
public List<string> names = new List<string>();
public String Get()
{
return "Hello I am Service";
}
public IEnumerable<string> Post([FromBody]string custName)
{
try
{
names.Add(custName);
return names;
}
catch(Exception ex)
{
return null;
}
}
}
I am using jQuery AJAX to post the values & it looks as below
var customerName = $('#txtName').val();
$.ajax(
{
url:"http://myip:8060/Api/Test",
method:"POST",
data:{'custName',customerName},
success:function(data)
{
console.log(data);
}
error:function(e)
{
console.log(e);
}
})
Now if I alert customerName, I am getting the correct value, but when I am returning the Post action of the controller is returning null as below
[null]
[null,null]
My question is why the values are getting null?
Try this in jQuery:
hmm the controller somehow gives an error when trying to do a post request. try this in your controller:
the html i use is the following:
change http://localhost:52016/api/values to your address edit 2: i noted the js is not jquery. But i got this to work.
Try this one:-
The model binder of ASP.NET Web API can't translate a JSON to a string, you must use an object to do this think.
So you have 3 options to fix your problem
First, use query string
In your action change the attribute
FromBody
toFromUri
, like thatThen change your javascript code
Second, use route attribute
Decorate your action with Route attribute like that
Then change your javascript code
Obs.: To use the
Route
attribute you must configure it in WebApiConfig, so you must have this line there:So your WebApiConfig should be like this
Third, use a view model class
Create a class
Receive this model in your action, using FromBody attribute
Then change your javascript code
Obs.: Your controller has a little bug
Each controller in Web API and MVC is created everytime when a request is handled by the server, so your names field in TestController class will be a new List in every request, if you want to keep data in this list other requests, make this static