Model becomes null when any of the parameters is null
Someone asked on Stack Overflow:
In my Angular 5 application, I would like to save an “event” object with the following method :
save(newEvent: NewEvent): Observable<any> { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; const requestUrl = 'api/event'; return this.http.post<any>(requestUrl, newEvent, httpOptions); }The NewEvent model is :
export class NewEvent { id: number; title: string;... constructor() { this.id = null; this.title = '';... } }And after I call this with a method in a controller with .NET Core :
[HttpPost("api/event")] public IDictionary<string, Object> SaveEvent([FromBody] EventViewModel model){...}The EventViewModel POCO is :
{ public class EventViewModel { public int Id { get; set; } public string Title { get; set; }... } }When my object
EventViewModelhas no attributes with a “null” value it works with no problems, but when I have “null” attributes it doesn’t work (theEventViewModelbecame “null”) and I want to have sometimes “null” attributes.
I posted the following answer, which was chosen as the accepted answer and received 2 upvotes:
Your C# model has a non-nullable int for the Id column. If you want it to be nullable (as you set it to null in your javascript model) you should define it as int? or Nullable<int>.
See also: Nullable Types.
Originally posted on Stack Overflow — 2 upvotes (accepted answer). Licensed under CC BY-SA.