Error assigning null to a nullable int - “The value 'null' is not valid for property”

后端 未结 6 769
耶瑟儿~
耶瑟儿~ 2020-12-28 16:50

I have this property in my view model:

[DisplayName(\"Region\")]
public int? RegionId { get; set; }

I pass my view model to my controller,

6条回答
  •  情深已故
    2020-12-28 17:44

    I think the issue is not assigning null, it's that the consuming code does not except a null value. The assignment is perfectly valid (although your null check is inverted, and the cast is redundant).

    viewModel.RegionId = null;
    

    As an aside you can use HasValue to check for null on a nullable type. Although in reality this it's no different to a null check, just looks a bit cleaner:

    if (viewModel.RegionId.HasValue)
    {
        // do something
    }
    

提交回复
热议问题