问题描述
现在我有一个属性 double Maximum
的ViewModel。在视图方面,它保留在隐藏的输入中,以帮助不显眼的验证。
当发布后备值时,绑定会以静默方式失败。我不得不在这一行上放一个断点:
if(ModelState.IsValid)
并检查哪个 ModelState
属性有错误。然后我发现这个 double Maximum
property has a error with the following message:
在视图侧检查 HTML
与我可以看到隐藏的输入有这个值:
1.79769313486232E + 308
其中正确表示常量。
我发现这个Scott Hanselman的帖子来自于2005年1月/ 2005年(几乎9年前),处理类似的事情:
我的应用程序配置有问题或从 strin直接转换g
回到 double
不支持?注意:我尝试使用Firebug更改隐藏的输入值,并以Scott的身份在他的帖子中做了说明。 :我从最后一位数字减去1 ...
1.79769313486231E + 308
并再次做了回发,只是为了找到这次正确处理的模型binder。
我使用 @ Html.HiddenFor
创建隐藏的输入。
在仔细阅读Scott的帖子后,我看到他提到了往返说明符。我还在StackOverflow上找到了。
所以我这样做:
@ Html.HiddenFor(m => m.Maximum,
new {Value = Model.Maximum.ToString(R)})
现在这给了我一个 double.MAX
字符串表示,可以回滚到控制器端的 double
:
1.7976931348623157E + 308
尼斯...问题解决了。
希望它帮助任何可能面临同样问题的人。
这是多么有趣!
1.79769313486232E + 308 // double。 MAX
1.7976931348623157E + 308 // double.MAX.ToString(R)
值得一提的是,所有这一切也适用于 double.MIN
。
Right now I have a ViewModel with a property double Maximum
. On the view side it's kept in a hidden input to help with unobtrusive validation.
When post backing the values, the binding silently fails. I had to put a breakpoint on this line:
if(ModelState.IsValid)
and check which ModelState
property had an error. Then I found that this double Maximum
property had an error with the following message:
On the view side inspecting the HTML
with Firebug I can see that the hidden input has this value:
1.79769313486232E+308
which correctly represents double.MAX constant.
I found this Scott Hanselman post from Jan/2005 (almost 9 years ago) which deals with something similar:
Is there something wrong with my app config or this direct conversion from string
back to double
is not supported? I think it should handle it without errors.
Note: I tried changing the hidden input value with Firebug and did as Scott mentions on his post: I subtracted 1 from the last digit...
1.79769313486231E+308
and did a postback again just to find the model binder handled it correctly this time.
I'm using @Html.HiddenFor
to create the hidden input.
After carefully reading Scott's post I saw that he mentions the round-trip specifier. I also found an example here on StackOverflow.
So I did this:
@Html.HiddenFor(m => m.Maximum,
new { Value = Model.Maximum.ToString("R") })
Now this gives me a double.MAX
string representation that can be round-tripped back to a double
on the controller side:
1.7976931348623157E+308
Nice... problem solved.
Hope it helps anyone that might face this same problem in the future.
How interesting this is?!
1.79769313486232E+308 // double.MAX
1.7976931348623157E+308 // double.MAX.ToString("R")
It's worth mentioning that all this is also applicable to double.MIN
.
这篇关于模型binder无法处理double.MAX字符串表示形式返回到double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!