asp.net mvc validation annotation for dollar currency

后端 未结 2 874
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-22 03:01

I am validation for Html.TextBoxFor. Here is my code on the view

@Html.TextBoxFor(m => m.Amount, new {@class = \"form-control\", Value = Stri         


        
2条回答
  •  不思量自难忘°
    2020-12-22 03:23

    You can create you own Binder object to handle this. First create this object:

    public class DoubleModelBinder : 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
        {
          if (!string.IsNullOrEmpty(valueResult.AttemptedValue))
            actualValue = Convert.ToDouble(valueResult.AttemptedValue.Replace("$", ""), System.Globalization.CultureInfo.CurrentCulture);
        }
        catch (FormatException e)
        {
          modelState.Errors.Add(e);
        }
    
        if (bindingContext.ModelState.ContainsKey(bindingContext.ModelName))
          bindingContext.ModelState[bindingContext.ModelName] = modelState;
        else
          bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
        return actualValue;
      }
    }
    

    Then in your Global.asax.cs file in the Application_Start function, add this:

    ModelBinders.Binders.Add(typeof(double?), new DoubleModelBinder());
    

提交回复
热议问题