当任何参数为空时,模型变为空

Model becomes null when any of the parameters is null

在我的 Angular 5 应用程序中,我想使用以下方法保存一个 "event" 对象:

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);
  }

NewEvent 模型是:

export class NewEvent {
  id: number;
  title: string;...

  constructor() {
    this.id = null;
    this.title = '';...
  }
}

在我使用 .NET Core 的控制器中的方法调用它之后:

[HttpPost("api/event")]
public IDictionary<string, Object> SaveEvent([FromBody] EventViewModel model){...}

EventViewModel POCO 是:

{
    public class EventViewModel
    {
        public int Id { get; set; }
        public string Title { get; set; }...
    }
}

当我的对象 EventViewModel 没有具有 "null" 值的属性时它可以正常工作,但是当我有 "null" 属性时它不起作用(EventViewModel 变成了 "null") 并且我有时想要 "null" 属性。

您的 C# 模型的 Id 列具有不可为 null 的 int。如果您希望它可以为空(因为您在 javascript 模型中将其设置为 null),您应该将其定义为 int?Nullable<int>.

另请参阅:Nullable Types.