ASP.NET Core Api parameter is null - asp.net-web-api

I have an API controller which has actions to get and post data. and I am trying to access GetProductById meyhod from ajax bu productId parameter is always equals to zero (0). When I want to call GetAll method with GET method everything is fine.
JavaScript code is like below
var product = JSON.stringify({ productId: id });
$http({
method: 'POST',
contentType: 'application/json',
url: '/api/Product/ProductInfo',
data: product
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log(response);
});
And API Controller is like below
[Route("api/Product")]
public class ProductController : BaseController
{
[HttpPost]
[Route("ProductInfo")]
public Product GetProductById([FromBody]int productId)
{
return UnitOfWork.GetRepository<Product>().FirstOrDefault(i => i.Id == productId);
}
[HttpGet]
[Route("GetAll")]
public string GetAll()
{
return "Can";
}
}
Can anyone say why that case is happening?

Although you are sending back a string representation of { productId: id } when the model is binded in the post method in the controller it is expecting an int. productId is barely the argument of that method, it doesn't define the parameter name you're supposed to send. Try sending just the id in the body instead of that json body { productId: id }.
If you want to send back a json body then the proper representation should be a class like the following for your post action
class ProductModel
{
int productId;
}
This would essentially make you able to parse your json payload the way you send it now, of course you can opt for custom model binders but that would be an overkill.
For example, if the id is 123 just use 123 as body, not { productId: 123 }

Related

How to pass List<T> from from JS to API

I have below model and Controller. I want to know how to pass value for the API from Ajax call.
Model:
Public Class Data
{
public int ID {get;set;}
public string Title {get;set;}
}
Controller:
[HTTPPOST]
public string UpsertItems(List<Data> Inputs)
{
try
{...}
catch(Exception ex)
{..}
}
From frontend i need to pass below data to API.
I tried passing data like below
var datacoll='{{"ID":1,"Title":"a"},{"ID":2,"Title":"b"}}'
If I pass variable datacoll as it is I am getting 500 internal error and if I pass JSON.Stringify(datacoll) in controller i am getting null value.
Ajax method:
$.ajax({
url: '/Test/UpsertItems',
method: 'POST',
dataType: 'text',
contentType: 'application/json; charset=utf-8',
data: datacoll,
success: function (data) {..},
error: function (jqXHR) {..},
});
Please let me know what is wrong in it.
Looks like your data needs to be a list, notice the square brackets.
var datacoll='[{"ID":1,"Title":"a"},{"ID":2,"Title":"b"}]'

Passing a boolean value to asp.net api controller via Ajax

I am trying to pass a single boolean value via ajax to a server API.
The API action is hitted but the parameter (shuffled) is false, though I am setting it to true via Ajax.
The api controller action is this:
[HttpPost("PostShuffled")]
public IActionResult PostShuffled([FromBody]bool shuffled)
{
userSession.Shuffled = shuffled;
return Ok();
}
My Ajax call is this:
function ChangeViewMode(el) {
if (el.id == "ViewShuffled") {
$.ajax({
url: "/api/Data/PostShuffled",
contentType: "application/json",
method: "POST",
data: JSON.stringify({ shuffled: true }),
success: function () { alert("ok"); }
});
}
}
My question is what am I doing wrong?
Ok I have solved the problem this way:
Defined a new class:
public class AjaxShuffled
{
public bool shuffled { get; set; }
}
Then in my controller changed:
[HttpPost("PostShuffled")]
public IActionResult PostShuffled([FromBody]AjaxShuffled s)
{
userSession.Shuffled = s.shuffled;
return Ok();
}
And now the value is passed correctly. I had to encapsulate the boolean into a class to make it work.
The problem is that shuffled is wrapped in an object instead of sent by itself. If you only want to send a boolean value, just send true or false itself: data: true or data: JSON.stringify(true) depending on how you've configured your web service to handle input formats for boolean. On the server side you should only need the [FromBody] descriptor on the API method parameter.

How to pass complex JSON object in mvc action method?

I have a situation where I get data from ajax call. I want to call an action method and pass data as arguments. The data passed to action method should be mapped to object properties in parameter list.
Here is my class which is called FullQuestion.
public class FullQuestion : Question
{
public string Title { get; set; }
public string Content { get; set; }
public List<Tag> Tags { get; set; }
}
Here is my Ajax call method
var finalTagResultText = {Title: "title", Content: "content",Tag: { tagName: "tname", tagDescription: "tdesc"},Tag: { tagName: "tname1", tagDescription: "tdesc1"}};
$.ajax({
url: '#Url.Action("AskQuestion", "Dashboard")',
type: "POST",
data: JSON.stringify(finalTagResultText),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
window.location.href = "#Url.Action("Questions", "Dashboard")";
}
});
Here is my action method.
[HttpPost]
[ActionName("AskQuestion")]
public void AskQuestion_Post(FullQuestion question)
{
}
I want to get the JSON object passed as a FullQuestion object. I used json2 library to make use of stingify method.
I get the title and content text but no Tag object.
Any idea how can i accomplish that ? Thanks in advance.
Your collection property is named Tags (not Tag) and since its a collection, you need to pass an array of Tag objects, for example
var finalTagResultText = { .... , Tags: [{ tagName: "tname", tagDescription: "tdesc"}, { tagName: "tname1", tagDescription: "tdesc1"}]}`
Side note: Your ajax success callback is redirecting to another page, in which case, do not use ajax to submit your data. The whole point of ajax is to stay on the same page. You would be better off just doing a standard submit and using a RedirectToAction() in your POST method.
You are using wrong JSON format, using correct format as follows:
{"Title": "title", "Content": "content","Tag":[{ "tagName": "tname", "tagDescription": "tdesc"},{ "tagName": "tname1", "tagDescription": "tdesc1"}]}
In order to verify your JSON string, you can use the below link
https://jsonformatter.curiousconcept.com/

MVC web api GET parameter is always null

Following is my ajax call
$.ajax({
type: "GET",
url: "https://localhost/api/Client",
data: JSON.stringify({"SortExpression":"clientName","SortDirection":"desc"}),
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
dataType:'json',
error: function (data) {
alert("hi error buddy")
},
success: function (response) {
if (response) {
//todo
}
}
});
And my controller
public List<Customer> Get([FromUri] SortFilter filter)
{
}
and my model
public class SortFilter
{
public string SortExpression
{
get; set;
}
public string SortDirection
{
get; set;
}
}
but my contoller always takes the parameters as NULL. where am I going wrong ?
You're supplying a value, but not a key. So while the model binder may be able to discern what a SortFilter is, it has no way of knowing what filter is.
Try wrapping the object and giving it a key name. Perhaps something like this:
JSON.stringify({"filter":{"SortExpression":"clientName","SortDirection":"desc"}})
GET requests are performed on the query string, which should not be JSON encoded. POST, and PUT data may be JSON encoded, but not GET. The reason your parameter is null is because the query string is a single string with no parameter name.
replace:
data:JSON.stringify({"SortExpression":"clientName","SortDirection":"desc"})
with
data:{"SortExpression":"clientName","SortDirection":"desc"}
You can check the WebAPI call directly by typing in the full URL to the web API method
https://localhost/api/Client?SortExpression=clientName&SortDirection=desc
This will allow you to debug your data retriever, and page separately which should make the whole process much easier.

Ajax PUT request to Web Api

I currently have a ajax request setup to send a "PUT" request to a web api in my mvc 4 project. My request is able to get into the method on the api but the parameter is always null. Any ideas why? I have also check the PUT request as its executed and it does send a string of key/value pairs for each form control. Here is my code:
Web Api method (selection is always null)
public void Put([FromBody]string selection)
{
}
Update:
I forgot I was doing a little debugging of my own. I have confirmed that when you serialize a form the param is named "selection". Please take another look.
Ajax call:
$.ajax({
type: "PUT",
url: urlPrefix + "api/file/Manipulate",
data: $("#frmManipulate").serialize(),
contentType: "application/json; charset=utf-8",
dataType: "json",
statusCode: {
204: function (jqXHR) {
alert("No file(s)/Directory(s) were selected.");
}
}
}).done(function () {
location.reload();
});
It's null because you aren't passing it:
data: { val1 : "test", val2 : "test2"}
Try:
data: { selection : "something" }
It is null because asp.net web api does not know how to deserialize the { val1 : "test", val2 : "test2"} to a string. You could use a DTO approuch to pass these information to the action, for sample:
in the web api project, add a class like this:
public class InfoDTO
{
public string val1 { get; set; }
public string val2 { get; set; }
// other properties if you need
}
And change your put action to get a parameter with this type:
public void Put([FromBody]InfoDTO info)
{
// use 'info' object
}
Your client-side javascript can keep with the same code.

Resources