2016-01-29 71 views
1

我验证了Html.TextBoxFor。这里是我的看法asp.net mvc美元货币验证注释

@Html.TextBoxFor(m => m.Amount, new {@class = "form-control", Value = String.Format("{0:C}", Model.Amount) }) 

此代码需要从数据库5000.00一样,并显示在用户界面上的双重价值为$ 5,000.00代码。但是,当用户点击提交按钮时,显示验证错误

值'$ 5,000.00'对金额无效。该示范

我的验证注解是

[Range(0, double.MaxValue, ErrorMessage = "Please enter valid dollar amount")] 

为了得到它提交,我不得不重新键入为5000.00。我怎样才能解决这个问题?谢谢。

+1

取看看这个http://stackoverflow.com/questions/34550361/how-do-i-properly-format-a-readonly-textboxfor-value-as-currency – Shyju

回答

0

您可以创建自己的Binder对象来处理这个。首先,创建该对象:

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; 
    } 
} 

然后在在Application_Start功能时,您的Global.asax.cs文件,补充一点:当你在htmlAttributes的value = string.Format("{0:C}", Model.Amount)

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

,剃刀将执行C#代码并返回值"$125.67"(假设Amount属性的值为125.67M),它是一个字符串。因此,通过您的视图生成的标记将

<input value="$125.67" class="form-control" id="Amount" name="Amount" type="text"> 

现在既然$125.67不是不是的Valide十进制值,而是一个字符串。它不能将此文本框的值映射到您的视图模型的Amount属性,该属性为十进制/双重类型。

你可以做的是,在你的视图模型中创建一个新的属性来存储这个格式化的字符串值,当用户提交表单时,尝试将它解析回一个十进制变量并使用它。

因此,一个新的属性添加到您的视图模型

public class CreateOrderVm 
{ 
    public int Id { set;get;} 
    public string AmountFormatted { set;get;} // New property 
    public decimal Amount { set;get;} 
} 

而且在你看来,这是强类型到CreateOrderVm

@model CreateOrderVm 
@using(Html.BeginForm()) 
{ 
    @Html.TextBoxFor(m => m.AmountFormatted, new { @class = "form-control", 
           Value = String.Format("{0:C}", Model.Amount) }) 

    <input type="submit" /> 
} 

而在你HttpPost行动

[HttpPost] 
public ActionResult Create(CreateOrderVm model) 
{ 
    decimal amountVal; 

    if (Decimal.TryParse(vm.AmountFormatted, NumberStyles.Currency, 
              CultureInfo.CurrentCulture, out amountVal)) 
    { 
     vm.Amount = amountVal; 
    } 
    else 
    { 
     //add a Model state error and return the model to view, 
    } 

    //vm.Amount has the correct decimal value now. Use it to save 
    // to do :Return something 
}