ASP MVC中的十进制数据输入

Voo*_*ild 4 asp.net jquery-plugins asp.net-mvc-2

public Decimal SalePrice { get; set; }
Run Code Online (Sandbox Code Playgroud)

<%= Html.TextBoxFor(Model => Model.SalePrice) %>
Run Code Online (Sandbox Code Playgroud)

什么是确保用户验证或输入正确的好方法?像只允许数字输入和最多两个小数点的事情?

Pan*_*cus 7

像下面这样的正则表达式应该有效:

\A\d+(\.\d{1,2})?\Z
Run Code Online (Sandbox Code Playgroud)

这匹配输入,如:

2.00
25.70
04.15
2.50
525.43
423.3
52
Run Code Online (Sandbox Code Playgroud)

而且,正如迈克建议的那样,您可以在数据验证属性中使用它:

[RegularExpression(@"\A\d+(\.\d{1,2})?\Z", ErrorMessage="Please enter a numeric value with up to two decimal places.")]
public Decimal SalePrice { get; set; }
Run Code Online (Sandbox Code Playgroud)

编辑:回答您的两个问题:

1)这在提交权上有效,而不是在我们失去该领域的焦点时?

假设您添加的所有内容都是属性,那么在提交时会进行肯定验证.从技术上讲,一旦表单参数绑定到模型,就会进行验证.但是,要实际使用它,您需要检查控制器中的验证参数:

public ActionResult MyController(MyModel model)
{
    if (ModelState.IsValid)
    {
        // do stuff
    }
    else
    {
        // Return view with the now-invalid model
        // if you've placed error messages on the view, they will be displayed
        return View(model);
    }
}
Run Code Online (Sandbox Code Playgroud)

除了服务器端之外,要在客户端进行验证,您需要使用javascript.使用Microsoft AJAX验证的一个基本示例是Scott Gu的博客.

2)你能告诉我最大入口不能超过100.00且最小入口不能低于1.00的正则表达式

你可能会以某种方式在正则表达式中执行此操作,但正则表达式并不是为模式匹配而设计的.除了regex属性之外,更好的方法是添加范围验证属性.所以现在你的房产看起来像:

[RegularExpression(@"\A\d+(\.\d{1,2})?\Z", ErrorMessage="Please enter a numeric value with up to two decimal places.")]
[Range(1.00m, 100.00m)]
public Decimal SalePrice { get; set; }
Run Code Online (Sandbox Code Playgroud)

上面的代码未经测试,但一般方法应该有效.