Asp.net mvc 十进制数的DataAnnotation显示格式
我有他的密码。 局部视图Asp.net mvc 十进制数的DataAnnotation显示格式,asp.net-mvc,data-annotations,Asp.net Mvc,Data Annotations,我有他的密码。 局部视图 <div class="input width110"> @Html.EditorFor(x => x.Price, @Html.Attributes(@class: "right_text_align", @disabled: "true", @id: "Price")) </div> 控制器 public ActionResult SetService(ServiceModel model, string action) {
<div class="input width110">
@Html.EditorFor(x => x.Price, @Html.Attributes(@class: "right_text_align", @disabled: "true", @id: "Price"))
</div>
控制器
public ActionResult SetService(ServiceModel model, string action)
{
if (ModelState.IsValid)
{
/*Does smthg.*/
ModelState.Clear();
}
return View("Index", rcpModel);
//Index is main view, which holds partialView
//rcpModel holds, model
}
当视图加载时,十进制以“0.00”格式显示。但在post之后,当modelState为无效数字时,以“0.0000”格式显示。如果模型状态有效,那么一切都会顺利进行。有人遇到过类似的情况吗?如果您使用javascript修改文本框(货币格式或逗号)上的值,则可能会出现绑定错误,因为它的行为类似于字符串。试试这个: 为十进制值创建BindingProperty
public class DecimalModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
var modelState = new ModelState { Value = valueResult };
object actualValue = null;
try
{
actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
CultureInfo.CurrentCulture);
}
catch (FormatException e)
{
modelState.Errors.Add(e);
}
bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
return actualValue;
}
}
在global.asax app\u start或WebActivator.PostApplicationStartMethod上添加一个条目以注册自定义活页夹:
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
如果javascript修改了文本框上的值(货币格式或逗号),那么可能会出现绑定错误,因为它将作为字符串。试试这个: 为十进制值创建BindingProperty
public class DecimalModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
var modelState = new ModelState { Value = valueResult };
object actualValue = null;
try
{
actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
CultureInfo.CurrentCulture);
}
catch (FormatException e)
{
modelState.Errors.Add(e);
}
bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
return actualValue;
}
}
在global.asax app\u start或WebActivator.PostApplicationStartMethod上添加一个条目以注册自定义活页夹:
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
在调用视图之前使用的代码的每个点中,显示点而不是逗号就足以将区域性更改为英语
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("En");
在调用视图之前使用的代码的每个点中,显示点而不是逗号就足以将区域性更改为英语
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("En");
您是否在该值中添加了其他内容?如果您有一个添加逗号的javascript插件,那么默认绑定器将无法工作Yes@amhed,我使用jQuery Globalize,因为我的原生格式是“0,00”。稍后我尝试验证这是否真的是活页夹问题。您是否向值中添加了其他内容?如果您有一个添加逗号的javascript插件,那么默认绑定器将无法工作Yes@amhed,我使用jQuery Globalize,因为我的原生格式是“0,00”。后来我试图验证这是否真的是活页夹问题。