Reputation: 11
I have an Angular 10 application that calls a .NET Core 3 API. I have a complex type that I am trying to model bind on a POST but running into an issue. On the Angular side, I have a type with an array and on the .NET side, the type I'm trying to bind to includes a List<>. I'm trying to get the array to model bind with the List<>. The array values are correct on the POST but I hit the error in the controller on the .NET side, specifically with the parameter when trying to bind. Below is the error I'm receiving along with my code.
Error....
" Bad Request status: 400"
"The JSON value could not be converted to App.Models.VideoCategoryModel[ ]"
Angular Types...
export class Video {
constructor(public id?: number,
public title?: string,
public date?: string,
public description?: string,
public url?: string,
public enabled?: boolean,
public categories?: VideoCategory[]){ }
}
export class VideoCategory {
constructor(public id?: number,
public name?: string){ }
}
Here is the JSON being sent to the API
{
"title":"Test Title",
"date":"2020-12-09",
"description":"Test Description",
"url":"C:\\fakepath\\Capture2.JPG",
"categories":{
"id":101,
"name":"Platform Tutorials"
}
}
.NET Core Controller Code....
Models...
public class VideoModel
{
public VideoModel()
{
Categories = new List<VideoCategoryModel>();
}
public int Id { get; set; }
public DateTime Date { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string VideoUrl { get; set; }
public bool Enabled { get; set; }
public List<VideoCategoryModel> Categories { get; set; }
}
public class VideoCategoryModel
{
public int Id { get; set; }
public string Name { get; set; }
}
Controller...
[HttpPost("addvideo")]
public IActionResult AddVideo([FromBody] VideoModel model)
{
try
{
//var id = _service.AddVideo(_mapper.Map<VideoModel, TaVideo>(model));
//return Ok(id);
return Ok();
}
catch(Exception ex)
{
return BadRequest($"Failed to add the new video: {ex}");
}
}
Any suggestions would be appreciated. I'm obviously missing something or need to refactor the way I'm binding but I don't know the best way to do it. Thanks in advance!
Upvotes: 1
Views: 791
Reputation: 27803
"The JSON value could not be converted to App.Models.VideoCategoryModel[ ]"
Based on your VideoModel
class, we can find that Categories
property should be a collection of VideoCategoryModel
object. As @MohsinMehmood mentioned in comment, you should provide an array for categories field on your Angular frontend code.
"categories":[{
"id":101,
"name":"Platform Tutorials"
}]
Besides, please note that you are passing file path in url
field, but the property is named as VideoUrl
in model class, to make model binding work well, you can try to specify the property name that is present in the JSON when serializing and deserializing with following code snippet.
[JsonPropertyName("Url")]
public string VideoUrl { get; set; }
Upvotes: 2