我有一个自定义模型类,其中包含一个十进制成员和一个接受此类条目的 View 。一切都很顺利,直到我添加了 JavaScript 来格式化输入控件内的数字。当焦点模糊时,格式代码用千位分隔符“,”格式化输入的数字。
问题是我的模态类中的十进制值没有与千位分隔符很好地绑定(bind)/解析。当我用“1,000.00”测试它时,ModelState.IsValid 返回 false,但它对“100.00”有效,无需任何更改。
如果您有任何解决方案,可以与我分享吗?
提前致谢。
示例类
public class Employee
{
public string Name { get; set; }
public decimal Salary { get; set; }
}
示例 Controller
public class EmployeeController : Controller
{
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult New()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult New(Employee e)
{
if (ModelState.IsValid) // <-- It is retruning false for values with ','
{
//Subsequence codes if entry is valid.
//
}
return View(e);
}
}
示例 View
<% using (Html.BeginForm())
{ %>
Name: <%= Html.TextBox("Name")%><br />
Salary: <%= Html.TextBox("Salary")%><br />
<button type="submit">Save</button>
<% } %>
<小时/>
我按照 Alexander 的建议尝试了使用 Custom ModelBinder 的解决方法。问题解决了。但该解决方案与 IDataErrorInfo 实现并不一致。由于验证而输入 0 时,Salary 值将变为空。请问有什么建议吗? Asp.Net MVC 团队成员会来 stackoverflow 吗?我可以从你那里得到一些帮助吗?
按照 Alexander 的建议使用自定义模型绑定(bind)器更新了代码
模型绑定(bind)器
public class MyModelBinder : DefaultModelBinder {
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
if (bindingContext == null) {
throw new ArgumentNullException("bindingContext");
}
ValueProviderResult valueResult;
bindingContext.ValueProvider.TryGetValue(bindingContext.ModelName, out valueResult);
if (valueResult != null) {
if (bindingContext.ModelType == typeof(decimal)) {
decimal decimalAttempt;
decimalAttempt = Convert.ToDecimal(valueResult.AttemptedValue);
return decimalAttempt;
}
}
return null;
}
}
员工类别
public class Employee : IDataErrorInfo {
public string Name { get; set; }
public decimal Salary { get; set; }
#region IDataErrorInfo Members
public string this[string columnName] {
get {
switch (columnName)
{
case "Salary": if (Salary <= 0) return "Invalid salary amount."; break;
}
return string.Empty;
}
}
public string Error{
get {
return string.Empty;
}
}
#endregion
}
最佳答案
其背后的原因是,在 ValueProviderResult.cs 的 ConvertSimpleType 中使用了 TypeConverter。
十进制类型转换器不支持千位分隔符。 阅读此处:http://social.msdn.microsoft.com/forums/en-US/clr/thread/1c444dac-5d08-487d-9369-666d1b21706e
我还没有检查,但在那篇文章中他们甚至说传递到 TypeConverter 的 CultureInfo 没有被使用。它永远是不变的。
string decValue = "1,400.23";
TypeConverter converter = TypeDescriptor.GetConverter(typeof(decimal));
object convertedValue = converter.ConvertFrom(null /* context */, CultureInfo.InvariantCulture, decValue);
所以我想你必须使用一种解决方法。不太好...
关于asp.net-mvc - Asp.Net MVC 中带有千位分隔符的十进制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/999791/