Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
@用于验证的Html.textbox_Html_Asp.net Mvc_Validation_String.format_Html.textboxfor - Fatal编程技术网

@用于验证的Html.textbox

@用于验证的Html.textbox,html,asp.net-mvc,validation,string.format,html.textboxfor,Html,Asp.net Mvc,Validation,String.format,Html.textboxfor,我有一个要求,比如@Html.TextBoxFor以逗号分隔的格式显示货币,不接受负值和特殊字符。在货币不可用的同时,我将此TextBoxFor的值更改为“不可用”。如何在视图中使用十进制验证和支持文本输入实现这一点 @Html.TextBoxFor(m => m.SourceCurrencyValue, new { @Value=String.Format("{ViewBag.decimalplace}",Model.SourceCurrencyValue) }) ViewBag.de

我有一个要求,比如
@Html.TextBoxFor
以逗号分隔的格式显示货币,不接受负值和特殊字符。在货币不可用的同时,我将此TextBoxFor的值更改为“不可用”。如何在视图中使用十进制验证和支持文本输入实现这一点

@Html.TextBoxFor(m => m.SourceCurrencyValue, new { @Value=String.Format("{ViewBag.decimalplace}",Model.SourceCurrencyValue) })

ViewBag.decimalplace
应该是小数点位置,如2或3。

您可以使用
正则表达式
-此表达式将小数位数限制为2,但会相应更改

[RegularExpression(@"^\d+,\d{0,2}$", 
     ErrorMessage = "Your error message")] 
public decimal SourceCurrencyValue { get; set; }
在看到您的评论进行澄清后,您可以使用上面的想法。“数据”属性在渲染元素时会在元素上创建数据属性,如果要在每个视图上执行此操作,为什么不尝试手动设置这些属性:

@{ var regex = string.Format(@"^\d+,\d{{0,{0}}}$", ViewBag.DecimalPlaces); }
@Html.TextBoxFor(model => model.SourceCurrencyValue, 
    new { data_val_regex_pattern = regex, data_val_regex = "Error message" })

这将根据您传入的数量更改小数位数。

我清楚地提到了如何在视图中实现这一点。我知道我可以在模型中使用正则表达式。但我希望这种逻辑发生在视图内部,就像我尝试过的那样。这是因为我从控制器动作传递十进制位置。对于不同的货币,情况会有所不同。所以我不能在模型中硬编码
{0,2}
。@Sandy实际上没有你问过如何在视图中实现它。我提出了另一种解决办法。您的问题中不清楚您是否希望以每种货币为基础进行此操作。@Sandy请参阅我的编辑,以获得更适合您的解决方案。这是否支持MVC3?@Sandy我本来会这么认为的