Reputation: 363
Where a model uses nullable values such as
public Nullable<int> Price { get; set; }
When adding new records all is fine, Price is Not a required field so will be saved as Null value in the database.
If I modify an existing record, let’s say I want to change the value of price from 10 to blank. Then I get a validation error.
Validation error: ‘Price‘ must be an integer between the values of -2147483648 and 2147483647
However this field is not required so I would have expected it to just save a null value?
Upvotes: 1
Views: 802
Reputation: 5773
That happens because empty textbox value is "" (empty string), but not null.
So, before setting new value you should check if value is empty string, if so - assign null manually.
Update for Knockout. You can write custom ko binding, that will do everything for you. Here is example (might be not the best one):
Javascript:
ko.bindingHandlers.nullableValue = {
init: function (element, valueAccessor, allBindingsAccessor) {
var underlyingObservable = valueAccessor();
var interceptor = ko.dependentObservable({
read: underlyingObservable,
write: function (value) {
if (value == '') {
underlyingObservable(null);
return;
}
underlyingObservable(value);
}
});
ko.bindingHandlers.value.init(element, function () { return interceptor; }, allBindingsAccessor);
},
update: ko.bindingHandlers.value.update
};
Html
<input type="text" data-bind="nullableValue: myNullableProperty" />
Hope it helps.
Upvotes: 4