I am trying to perform a search functionality in Asp.net core, this is my controller
[HttpPost("searchbyname")]
public async Task<ActionResult<List<SelectedChildDto>>> SearchByName([FromBody]string firstName)
{ if (string.IsNullOrWhiteSpace(firstName)) { return new List<SelectedChildDto>(); }
return await _context.Children
.Where(x => x.FirstName.Contains(firstName))
.OrderBy(x => x.FirstName)
.Select(x => new SelectedChildDto { Cld = x.Cld, ChildCode = x.ChildCode,
FirstName = x.FirstName, PhotoPath = x.PhotoPath })
.Take(5)
.ToListAsync();
}
I have this DTO class from the model
namespace API.Dtos
{
public class SelectedChildDto
{
public int Cld { get; set; }
public string ChildCode { get; set; }
public string FirstName { get; set; }
public string PhotoPath { get; set; }
}
}
"errors": {
"$": [
"The JSON value could not be converted to System.String. Path: $ | LineNumber: 0 | BytePositionInLine: 1."
]
}
2
Answers
I don’t know how you pass
firstName
in your view, but your data format is not correct.If you just passed a string
firstName
without[FromBody]
,You can refer to the following code.Controller:
View:
Test Result:
And if you wish to use
[FromBody]
, you can refer to the following code.Controller:
View:
Test Result:
The problem is related to System.Text.Json deserialization of body text for the single
[FromBody] string firstName
argument of your controller. For example, you need just to send"John"
in body instead of full-featured JSON{"firstName": "John"}
.Check also this answer to the similar question.