我有一个自定义的类型,其中包含一个小的成员,以接受入门用于这一类。一切都很好直到我加入javascript的格式内的数量输入控制。格式码格式输入的数千分离器','当聚焦模糊。

该问题是十进制的价值在我的模式类不bind/分析以及与千分离器。ModelState.IsValid假返回时,我的测试,它以"1 000个。00",但它是有效的"100.00"没有任何变化。

可能你与我分享如果你有任何解决方案了吗?

在此先感谢。

样品类

public class Employee
{
    public string Name { get; set; }
    public decimal Salary { get; set; }
}

样品控制器

public class EmployeeController : Controller
{
    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult New()
    {
        return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult New(Employee e)
    {
        if (ModelState.IsValid) // <-- It is retruning false for values with ','
        {
            //Subsequence codes if entry is valid.
            //
        }
        return View(e);
    }
}

样品图

<% using (Html.BeginForm())
   { %>

    Name:   <%= Html.TextBox("Name")%><br />
    Salary: <%= Html.TextBox("Salary")%><br />

    <button type="submit">Save</button>

<% } %>

我尝试解决方法与定义ModelBinder作为亚历山大建议。该probelm解决。但是,该解决方案不去好IDataErrorInfo执行情况。薪金值变得空的时候0输入由验证。任何建议吗?做Asp.Net 视的团队成员来计算器?我能从你的一点帮助?

新代码定义的模式粘合剂作为亚历山大建议

模型的粘合剂

public class MyModelBinder : DefaultModelBinder {

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
        if (bindingContext == null) {
            throw new ArgumentNullException("bindingContext");
        }

        ValueProviderResult valueResult;
        bindingContext.ValueProvider.TryGetValue(bindingContext.ModelName, out valueResult);
        if (valueResult != null) {
            if (bindingContext.ModelType == typeof(decimal)) {
                decimal decimalAttempt;

                decimalAttempt = Convert.ToDecimal(valueResult.AttemptedValue);

                return decimalAttempt;
            }
        }
        return null;
    }
}

雇员类

    public class Employee : IDataErrorInfo {

    public string Name { get; set; }
    public decimal Salary { get; set; }

    #region IDataErrorInfo Members

    public string this[string columnName] {
        get {
            switch (columnName)
            {
                case "Salary": if (Salary <= 0) return "Invalid salary amount."; break;
            }
            return string.Empty;
        }
    }

    public string Error{
        get {
            return string.Empty;
        }
    }

    #endregion
}
有帮助吗?

解决方案

似乎总有为了使默认的模型绑定高兴能够找到某种形式的解决方法!我想知道,如果你能创建一个由模型绑定只用了一个“伪”属性? (注意,这绝不是优雅。我自己,我似乎采取类似的把戏像这样越来越多的往往只是因为他们的工作,他们得到“完成”的工作......)还请注意,如果你使用一个单独的“视图模型”(我推荐这个),你可以把这个代码在那里,并留下您的域模型非常干净。

public class Employee
{
    private decimal _Salary;
    public string MvcSalary // yes, a string. Bind your form values to this!
    {
        get { return _Salary.ToString(); }
        set
        { 
            // (Using some pseudo-code here in this pseudo-property!)
            if (AppearsToBeValidDecimal(value)) {
                _Salary = StripCommas(value);
            }
        }
    }
    public decimal Salary
    {
        get { return _Salary; }
        set { _Salary = value; }
    }
}

P.S,我打这件事后,我在现在回头看,我连犹豫是否要发布此,它是如此的丑陋!但如果你认为它可能是有帮助的,我会让你决定...

祝您好运!点击 -Mike

其他提示

其背后的原因是,在ConvertSimpleType在ValueProviderResult.cs的TypeConverter,被使用。

十进制的TypeConverter的不支持千个隔板。 在这里阅读一下: HTTP: //social.msdn.microsoft.com/forums/en-US/clr/thread/1c444dac-5d08-487d-9369-666d1b21706e

我没有检查呢,但是在那个岗位,他们甚至说CultureInfo的传递到未使用的TypeConverter。它将永远是不变量。

           string decValue = "1,400.23";

        TypeConverter converter = TypeDescriptor.GetConverter(typeof(decimal));
        object convertedValue = converter.ConvertFrom(null /* context */, CultureInfo.InvariantCulture, decValue);

所以我想你必须使用一种解决方法。不是很好......

我不喜欢上面的解决方案,并与本想出了:

在我的自定义ModelBinder的,我基本上取代与文化价值不变的值,如果它是一个小数,然后移交工作,默认模式粘结剂的其余部分。 该rawvalue是一个阵列觉得奇怪,我,但是这是我所看到的/在原代码偷走了。

        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if(bindingContext.ModelType == typeof(decimal) || bindingContext.ModelType==typeof(Nullable<decimal>))
        {
            ValueProviderResult valueProviderResult = bindingContext.ValueProvider[bindingContext.ModelName];
            if (valueProviderResult != null)
            {
                decimal result;
                var array = valueProviderResult.RawValue as Array;
                object value;
                if (array != null && array.Length > 0)
                {
                    value = array.GetValue(0);
                    if (decimal.TryParse(value.ToString(), out result))
                    {
                        string val = result.ToString(CultureInfo.InvariantCulture.NumberFormat);
                        array.SetValue(val, 0);
                    }
                }
            }
        }
        return base.BindModel(controllerContext, bindingContext);
    }

你尝试将其转换控制器为十进制?这应该做的伎俩:

的字符串_val = “1,000.00”; 小数_decVal = Convert.ToDecimal(_val); Console.WriteLine(_decVal.ToString());

我实现自定义验证,增加分组的有效性。 问题(即我在下面的代码来解决)是解析方法除去所有数千个分离器,所以还1,2,2被认为是有效的。

下面我的粘合剂小数

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace EA.BUTruck.ContactCenter.Model.Extensions
{
 public class DecimalModelBinder : IModelBinder
 {
    public object BindModel(ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
        ValueProviderResult valueResult = bindingContext.ValueProvider
            .GetValue(bindingContext.ModelName);
        ModelState modelState = new ModelState { Value = valueResult };
        object actualValue = null;
        try
        {
            var trimmedvalue = valueResult.AttemptedValue.Trim();
            actualValue = Decimal.Parse(trimmedvalue, CultureInfo.CurrentCulture);

            string decimalSep = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
            string thousandSep = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator;

            thousandSep = Regex.Replace(thousandSep, @"\u00A0", " "); //used for culture with non breaking space thousand separator

            if (trimmedvalue.IndexOf(thousandSep) >= 0)
            {
                //check validity of grouping thousand separator

                //remove the "decimal" part if exists
                string integerpart = trimmedvalue.Split(new string[] { decimalSep }, StringSplitOptions.None)[0];

                //recovert double value (need to replace non breaking space with space present in some cultures)
                string reconvertedvalue = Regex.Replace(((decimal)actualValue).ToString("N").Split(new string[] { decimalSep }, StringSplitOptions.None)[0], @"\u00A0", " ");
                //if are the same, it is a valid number
                if (integerpart == reconvertedvalue)
                    return actualValue;

                //if not, could be differences only in the part before first thousand separator (for example original input stirng could be +1.000,00 (example of italian culture) that is valid but different from reconverted value that is 1.000,00; so we need to make a more accurate checking to verify if input string is valid


                //check if number of thousands separators are the same
                int nThousands = integerpart.Count(x => x == thousandSep[0]);
                int nThousandsconverted = reconvertedvalue.Count(x => x == thousandSep[0]);

                if (nThousands == nThousandsconverted)
                {
                    //check if all group are of groupsize number characters (exclude the first, because could be more than 3 (because for example "+", or "0" before all the other numbers) but we checked number of separators == reconverted number separators
                    int[] groupsize = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes;
                    bool valid = ValidateNumberGroups(integerpart, thousandSep, groupsize);
                    if (!valid)
                        throw new FormatException();

                }
                else
                    throw new FormatException();

            }


        }
        catch (FormatException e)
        {
            modelState.Errors.Add(e);
        }

        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
        return actualValue;
    }
    private bool ValidateNumberGroups(string value, string thousandSep, int[] groupsize)
    {
        string[] parts = value.Split(new string[] { thousandSep }, StringSplitOptions.None);
        for (int i = parts.Length - 1; i > 0; i--)
        {
            string part = parts[i];
            int length = part.Length;
            if (groupsize.Contains(length) == false)
            {
                return false;
            }
        }

        return true;
    }
 }
}

有关小数?可空的,你需要之前

添加一些代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace EA.BUTruck.ContactCenter.Model.Extensions
{
 public class DecimalNullableModelBinder : IModelBinder
 {
    public object BindModel(ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
        ValueProviderResult valueResult = bindingContext.ValueProvider
            .GetValue(bindingContext.ModelName);
        ModelState modelState = new ModelState { Value = valueResult };
        object actualValue = null;
        try
        {
             //need this condition against non nullable decimal
             if (string.IsNullOrWhiteSpace(valueResult.AttemptedValue))
                return actualValue;
            var trimmedvalue = valueResult.AttemptedValue.Trim();
            actualValue = Decimal.Parse(trimmedvalue,CultureInfo.CurrentCulture);

            string decimalSep = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
            string thousandSep = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator;

            thousandSep = Regex.Replace(thousandSep, @"\u00A0", " "); //used for culture with non breaking space thousand separator

            if (trimmedvalue.IndexOf(thousandSep) >=0)
            {
                //check validity of grouping thousand separator

                //remove the "decimal" part if exists
                string integerpart = trimmedvalue.Split(new string[] { decimalSep }, StringSplitOptions.None)[0];

                //recovert double value (need to replace non breaking space with space present in some cultures)
                string reconvertedvalue = Regex.Replace(((decimal)actualValue).ToString("N").Split(new string[] { decimalSep }, StringSplitOptions.None)[0], @"\u00A0", " ");
                //if are the same, it is a valid number
                if (integerpart == reconvertedvalue)
                    return actualValue;

                //if not, could be differences only in the part before first thousand separator (for example original input stirng could be +1.000,00 (example of italian culture) that is valid but different from reconverted value that is 1.000,00; so we need to make a more accurate checking to verify if input string is valid


                //check if number of thousands separators are the same
                int nThousands = integerpart.Count(x => x == thousandSep[0]);
                int nThousandsconverted = reconvertedvalue.Count(x => x == thousandSep[0]);

                if(nThousands == nThousandsconverted)
                {
                    //check if all group are of groupsize number characters (exclude the first, because could be more than 3 (because for example "+", or "0" before all the other numbers) but we checked number of separators == reconverted number separators
                    int[] groupsize = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes;
                    bool valid = ValidateNumberGroups(integerpart, thousandSep, groupsize);
                    if (!valid)
                        throw new FormatException();

                }
                else
                    throw new FormatException();

            }


        }
        catch (FormatException e)
        {
            modelState.Errors.Add(e);
        }

        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
        return actualValue;
    }

    private bool ValidateNumberGroups(string value, string thousandSep, int[] groupsize)
    {
        string[] parts = value.Split(new string[] { thousandSep }, StringSplitOptions.None);
        for(int i = parts.Length-1; i > 0; i--)
        {
            string part = parts[i];
            int length = part.Length;
            if (groupsize.Contains(length) == false)
            {
                return false;
            }
        }

        return true;
    }
 }

}

您需要创建双,双浮?类似粘合剂,浮? (代码是相同的DecimalModelBinder和DecimalNullableModelBinder的;你只需要在2点处有“小数”取代型)。

然后,在global.asax中

ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
ModelBinders.Binders.Add(typeof(decimal?), new DecimalNullableModelBinder());
ModelBinders.Binders.Add(typeof(float), new FloatModelBinder());
ModelBinders.Binders.Add(typeof(float?), new FloatNullableModelBinder());
ModelBinders.Binders.Add(typeof(double), new DoubleModelBinder());
ModelBinders.Binders.Add(typeof(double?), new DoubleNullableModelBinder());

该解决方案使用jQuery全球化与我的固定位置报道工作在服务器端细,像客户端部分 https://github.com/globalizejs/globalize/issues/73#issuecomment- 275792643个

嘿我有一个更想...这个基础上Naweed的答案,但仍然会让你的默认使用的模式粘合剂。这个概念是截取的发布形态,修改某些价值观,在它,然后通过的[修改]的形式收集到的UpdateModel(默认的模式粘合剂)的方法...我使用一种修改版的这个 处理框/布尔, ,可以避免的情况下任何其他的"真实"或"虚假",将导致未经处理/沉默的异常模型内的粘合剂。

(你当然会想到"重构"这个更重复使用,也许处理 所有 小数)

public ActionResult myAction(NameValueCollection nvc)
{
    Employee employee = new Employee();
    string salary = nvc.Get("Salary");
    if (AppearsToBeValidDecimal(salary)) {
        nvc.Remove("Salary");
        nvc.Add("Salary", StripCommas(salary));
    }
    if (TryUpdateModel(employee, nvc)) {
        // ...
    }
}

P.S.,我可能会被混淆在我NVC方法,但我认为这些会工作。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top