ASP.Net Web API [FromBody] parameter is not being Mapped.
I was creating a Web API for TheMemorium project.
Description: This Web API exposes the search functionality of The Memorium.com. I was having an issue with mapping the [FromBody] keyword from the data json data that I have in the Ajax call.
Here's the code on the API Controller:
// POST api/obituary
public ListPost([FromBody]string keyword, int pageNo, int Not)
{
Listresult = new List ();
int total = 0;
if (!string.IsNullOrWhiteSpace(model.SearchValue))
{
result = ObituaryService.SearchObituary(keyword, pageNo, Not);
if (model.Not > 0)
{
result = result.Where(x => x.MemorialId != model.Not).ToList();
total = total - 1;
}
}
return result;
}
Client Side Code :
$("#btnSearch").click(function () {
$.ajax({
url: 'api/Obituary/?pageNo=1&Not=1',
data: { keyword: $("#Searchkey").val()},
type: 'POST',
success: function (data) {
$("#searchContainer").html(JSON.stringify(data));
}
});
});
In the above code, whenever I call the ajax and post the data to the server, I would always end up with the keyword being null and the rest of the parameter having the passed value. What could be wrong? after some careful research. I was able to find out that [FromBody] parameter should be mapped using json with empty string = value ({' ':value})
$("#btnSearch").click(function () {
$.ajax({
url: 'api/Obituary/?pageNo=1&Not=1',
data: { '': $("#Searchkey").val()},
type: 'POST',
success: function (data) {
$("#searchContainer").html(JSON.stringify(data));
}
});
});
I was able to figure out also that I wouldn't have an issue if I was using a Complex Object and not primitive type such as a string, say you have SearchParameter as an object with Keyword, PageNo, and Not as Fields and you pass it using normal JSON in the ajax call it would have save me a lot of trouble.
Comments