2012-03-27 29 views
3

我對提交的表單信息存在問題。當我嘗試解析通過Interner Explorer或Chrome,但不在Firefox或Safari上返回的字符串時,Decimal解析失敗。這些字符串在Visual Studio中看起來完全一樣。當試圖用錯誤解析小數出asd4MVC3:提交字符串 - 在IE和Chrome上解析失敗

var asd3 = collection["formValue"]; // Get it from the FormCollection 
var asd4 = asd3.Replace(",", "."); // Change the punctuation 
var asd5 = Decimal.Parse(asd4);  // Make the string into a decimal 
var asd6 = Math.Round(asd5, 1);  // Round it 

它未能對asd5Input string was not in a correct format.

這裏的字符串的圖像我做了這個調試位。頂部是Firefox和低於Internet Explorer。

enter image description here

在地球上可能是什麼問題就在這裏?

+0

始終使用特定的文化信息解析數字。例如:'Decimal.Parse(number,new CultureInfo(「en-US」))''。如果兩個示例中的輸入都是「5.5」,那麼當您指定文化信息時,它永遠不會失敗。 – 2012-03-27 12:42:18

回答

2

What on earth could be the problem here?

文化。

在您的調試器中檢查Thread.CurrentThread.CurrentCulture的值,您將看到您的瀏覽器之間的差異。

如果您在您的瀏覽器不同的文化集這種文化將通過ASP.NET解析值時,特別是如果你沒有明確規定在你的web.config文化中:

<globalization culture="en-US" uiCulture="en-US" /> 

如果這被設置爲auto然後將使用瀏覽器文化。

另一種可能是在解析時強制不變的文化,以確保.(點)將成爲小數點分隔符。

var asd5 = Decimal.Parse(asd4, CultureInfo.InvariantCulture); 
+0

是的!這解決了它,將web.config的文化從自動改爲定義的文化。謝謝! – Esa 2012-03-27 12:51:08