Why is the parameter always null when I call the below Post method with the below ajax?
public IEnumerable<string> Post([FromBody]string value) { return new string[] { "value1", "value2", value }; }
Here is the call to the Web API method via ajax:
function SearchText() { $("#txtSearch").autocomplete({ source: function (request, response) { $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "api/search/", data: "test", dataType: "text", success: function (data) { response(data.d); }, error: function (result) { alert("Error"); } }); } }); }
Simply add parameterName = null in your route parameter. Another option is add an overload. Have 2 function names receive different parameters.
Optional Parameters in Web API Attribute Routing and Default Values: You can make a URI parameter as optional by adding a question mark (“?”) to the route parameter. If you make a route parameter as optional then you must specify a default value by using parameter = value for the method parameter.
Passing Data in your API Calls REST API endpoints can pass data within their requests through 4 types of parameters: Header, Path, Query String, or in the Request Body.
The [FromBody] attribute can be applied on only one primitive parameter of an action method. It cannot be applied to multiple primitive parameters of the same action method.
$.ajax({ url: '/api/search', type: 'POST', contentType: 'application/x-www-form-urlencoded; charset=utf-8', data: '=' + encodeURIComponent(request.term), success: function (data) { response(data.d); }, error: function (result) { alert('Error'); } });
Basically you can have only one parameter of scalar type which is decorated with the [FromBody]
attribute and your request needs to use application/x-www-form-urlencoded
and the POST payload should look like this:
=somevalue
Notice that contrary to standard protocols the parameter name is missing. You are sending only the value.
You can read more about how model binding in the Web Api works in this article
.
But of course this hacking around is a sick thing. You should use a view model:
public class MyViewModel { public string Value { get; set; } }
and then get rid of the [FromBody]
attribute:
public IEnumerable<string> Post(MyViewModel model) { return new string[] { "value1", "value2", model.Value }; }
and then use a JSON request:
$.ajax({ url: '/api/search', type: 'POST', contentType: 'application/json; charset=utf-8', data: JSON.stringify({ value: request.term }), success: function (data) { response(data.d); }, error: function (result) { alert('Error'); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With