मैंने इस मुद्दे को एक वास्तविक परियोजना में फिर से संशोधित किया है और अंत में एक कार्य समाधान मिला है।
using System.Globalization;
using System.Web.Mvc;
public class DecimalModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
object result = null;
// Don't do this here!
// It might do bindingContext.ModelState.AddModelError
// and there is no RemoveModelError!
//
// result = base.BindModel(controllerContext, bindingContext);
string modelName = bindingContext.ModelName;
string attemptedValue =
bindingContext.ValueProvider.GetValue(modelName).AttemptedValue;
// Depending on CultureInfo, the NumberDecimalSeparator can be "," or "."
// Both "." and "," should be accepted, but aren't.
string wantedSeperator = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
string alternateSeperator = (wantedSeperator == "," ? "." : ",");
if (attemptedValue.IndexOf(wantedSeperator) == -1
&& attemptedValue.IndexOf(alternateSeperator) != -1)
{
attemptedValue =
attemptedValue.Replace(alternateSeperator, wantedSeperator);
}
try
{
if (bindingContext.ModelMetadata.IsNullableValueType
&& string.IsNullOrWhiteSpace(attemptedValue))
{
return null;
}
result = decimal.Parse(attemptedValue, NumberStyles.Any);
}
catch (FormatException e)
{
bindingContext.ModelState.AddModelError(modelName, e);
}
return result;
}
}
फिर Global.asax.cs में Application_Start में
():
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());
उचित समाधान प्रकार decimal
(और decimal?
यदि आप उन्हें प्रयोग कर रहे हैं) के लिए एक कस्टम मॉडल बांधने की मशीन है ध्यान दें कि कोड मेरा नहीं है, मैं वास्तव में इसे क्रिस्टोफ नीरिनक के ब्लॉग here पर मिला। मैंने बस कुछ पंक्तियों को संपादित किया है और एक विशिष्ट डेटा प्रकार के लिए बाइंडर जोड़ रहा हूं, डिफ़ॉल्ट बाइंडर को प्रतिस्थापित नहीं कर रहा हूं।
स्रोत
2011-02-25 12:51:14
मैंने अपने जवाब को कोड में एक अतिरिक्त चेक जोड़ने के लिए अद्यतन किया है ताकि इसे ठीक से संगत गुणों को संभाल सकें। मैंने पाया कि यदि इसे प्रयास किए गए मान के रूप में एक खाली स्ट्रिंग मिली तो यह एक अपवाद फेंक देगा भले ही संपत्ति बंधी जा सके। अब यह ठीक काम करना चाहिए। –
एक पूरक क्लाइंट साइड फिक्स है जिसे इस के साथ लागू किया जाना चाहिए। आप इसे यहाँ मिल जाएगा: http://stackoverflow.com/a/8102159/41420 –
स्ट्रिंग इनपुट – Furtiro