Elegant way to wrap binding for unsupported type
I get it, this is work in progress. So this will be solved in future I guess:
<input bind="@Amount" /><br/>
@functions
{
public decimal Amount { get; set; }
}
Now throws:
Error: System.ArgumentException: 'bind' does not accept values of type System.Decimal. To read and write this value type, wrap it in a property of type string with suitable getters and setters
So I can make this work by adding this property (needs more failure checks, I know);
public decimal Amount { get; set; }
[NotMapped]
public string AmountStr
{
get
{
return this.dec.ToString();
}
set
{
this.dec = Convert.ToDecimal(value);
}
}
And binding to AmountStr.
But if you are using (EF poco) objects this really pollutes my model classes. Does anybody can suggest a elegant workaround for this?
I guess you could use Format
Looks like that (atm) is only for dates:
Data binding works with DateTime format strings (but not other format expressions at this time, such as currency or number formats):
I will try to pull a fix for this shortly. This still need to be confirmed by Blazor team.
I may imagine the problem about currency, but i don't see why it would be problem about decimal. Incorrect format ("," instead of "." depending to culture) seem to fallback to a wrong but valid value.
But actually, this pull request does not cover forbidding user to write text instead of number, and it will throw an exception in the console.
@SteveSandersonMS Would it be nice to add some sanity check on the input value (using TryParse instead of Parse) ? This way, even if "blocking" user from inputing wrong type value in the field is not possible at the moment, we may try to fallback to the previous valid value.
Of course it's only temporaly. I think we can assume that we may block the typo by some html attribute (input type='number' etc.), even if i have no clue about the behavior if the separator for float/double/decimal is different according to the culture. But it's not related to Blazor btw.
Binding support for decimal/number/int would indeed be the most elegant :-) thanks for that.
But doesn't your PR need any extra unittests?
I think you should be right about unit test, i mean, the current unit test pass, but i imagine some test need to be added to the scenario for that.
The only test i have made, it's to test a similar scenario of your on my own project, and see binding values/exception etc.
But i suspect that the result should not be very different from what actually existing...Except the current thread culture behavior for number separator, of course. The int implementation was already there.
If i can have some review from Blazor team it would be great, i don't think i'm an expert about the unit test project.
Closing in favour of aspnet/Blazor#630. @Daddoon - thanks for contributing that. We'll take a look.