Reputation: 56
I've been searching for a while and nothing helped me to solve this problem. I don't know what is happening, I used to send information to controller through a data object from AJAX using JQuery, but in this case, the parameter arrive null. My request look like this (I created a function based on button click):
Js Method on Razor page
const searchStudy = () => {
let searchString = JSON.stringify({"searchString": $("#searchString").val()});
console.log(searchString)
$.ajax({
url: "@Url.Action("SearchStudies","Studies")",
method: "POST",
processData: false,
data: searchString,
contentType: "application/json; charset=UTF-8",
dataType: "html",
success: function(response) {
console.log(response)
$("#dataContainer").html(response);
}
});
}
Controller
[HttpPost]
public async Task<IActionResult> SearchStudies(string searchString)
{
if (String.IsNullOrWhiteSpace(searchString))
return BadRequest("Search something!");
var studies = await _studyService.GetSearchStudies(searchString);
return PartialView("~/Views/Studies/_Studies.cshtml", studies);
}
Ps.: When I try to use query data on url it works. Hope some of you have face this problem once :)
Upvotes: 1
Views: 947
Reputation: 11
$.ajax({
url: "/Studies/SearchStudies/?searchString=" + searchString,
// ...
})
Upvotes: 0
Reputation: 51220
Create a model class for the expected object to be received.
public class SearchStudiesModel
{
public string SearchString { get; set; }
}
Change the controller method signature to expect to receive SearchStudiesModel
and apply [FromBody]
to get the value from the request body.
[HttpPost]
public async Task<IActionResult> SearchStudies([FromBody]SearchStudiesModel model)
{
if (String.IsNullOrWhiteSpace(model.SearchString))
return BadRequest("Search something!");
...
}
Debugging result
Upvotes: 1