In asp.net core, are empty string converted to NULL?

混江龙づ霸主 提交于 2021-01-01 04:38:52

问题


Assuming I have a form, and the value of "" is selected when the form is sent from the view to the controller to the action method, will asp.net core convert the empty string to a NULL value?

If I do not make the Boolean property nullable for the [required] attribute, it gives me this error: The value '' is invalid.

Does this mean that: "" is evaluated as NULL, the Boolean property does not allow NULL, asp.net core returns a error saying that you can not pass a empty string to the Model property because it is not nullable because asp.net core converts the empty string to a NULL?


回答1:


The first thing you need to understand is that the Options field here is the type of bool(not string).

The only content it can receive is true or false or null, whether you enter an empty string or a string other than true or false, it will recognized as null.

The attribute of Reuqired indicates that the Options field cannot be null,because Options is a bool type, so after you enter an empty string, the empty string is converted to a null value, and due to the restriction of the reuqired attribute, it cannot be null, so it will remind you invalid.

If you want to allow Options to receive null values, you only need to remove the reuqired attribute.

In the premise of the Required attribute limitation, I did a code test, you can refer to:




回答2:


MVC model binding does support binding an empty string as either a null or empty string, depending on metadata.

You can control that behaviour per field with attributes;

[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Property { get; set; }

Or override that behaviour globally by implementing a custom IDisplayMetadataProvider. Or even by providing your own IModelBinder / IModelBinderProvider.




回答3:


No they are not - the message says "The value '' is invalid." which is how an empty string looks like.




回答4:


you need to set value for boolean if you don't want to set required field. You need to send false if it is empty.



来源:https://stackoverflow.com/questions/60735864/in-asp-net-core-are-empty-string-converted-to-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!