【问题标题】:DataFormatString: the field must be a numberDataFormatString:字段必须是数字
【发布时间】:2015-04-06 14:56:38
【问题描述】:

我有这个模型:

[DisplayFormat(DataFormatString = "{0:c}", ApplyFormatInEditMode = true)]
public decimal SpotPrice { get; set; }

在我的详细信息视图中,价格显示为“25,00”。当我尝试编辑价格时,该字段预先填充了数据库条目“25,00”。当我立即点击保存时,我收到此错误:"The field SpotPrice must be a number."

根据question 中给出的建议,我在 Web.Config 中设置了我的全球文化:

<system.web>
<globalization culture="nl-NL"/>
</system.web>

我也尝试了许多不同的 DataFormatStrings,但没有一个能让我摆脱该错误消息。

我使用 SQL Server 来存储价格。

编辑:更新了问题: 我该怎么做才能正确验证此价格字段?

编辑:这是我用来保存新价格的编辑方法:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "CampingSpotId,SpotName,FieldName,Surface,Wifi,Water,Sewer,Reserved,Booked,SpotPrice,Type")] CampingSpot campingSpot)
{
    if (ModelState.IsValid)
    {
        _campingspotrepository.SetModified(campingSpot);
        return RedirectToAction("Index");
    }
    return View(campingSpot);
}

SetModified 方法这样做:

public void SetModified(CampingSpot campingSpot)
{
    db.Entry(campingSpot).State = EntityState.Modified;
    db.SaveChanges();
}

【问题讨论】:

  • 点击保存时会发生什么?
  • 我收到此错误"The field price must be a number" piclair.com/data/2c6in.jpg
  • 也就是说根本不保存
  • 我的意思是,执行保存操作的代码是什么?
  • @Moby Disk,我也可以忽略它。当我根本不使用 DataFormatString 时,似乎同样的行为也适用。此处失败的是 HTML 验证。

标签: c# sql-server asp.net-mvc culture


【解决方案1】:

你必须在模型中写[DataType(DataType.Currency)]

[DataType(DataType.Currency)]
public decimal SpotPrice { get;set;}

【讨论】:

    【解决方案2】:

    我在货币和日期格式方面遇到了同样的问题。如果没有人有合适的解决方案,解决方法是将 SpotPrice 设为字符串并在服务器端对其进行验证:

     public string SpotPriceStr { get; set; }
    

    在控制器中,转换为十进制,如果失败,向 ModelState 添加错误。

    【讨论】:

      猜你喜欢
      • 2015-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多