我在MVC 4.0中使用DataAnnotations验证,我有如下属性:
[Range(typeof(Decimal), "0.001", "9999", ErrorMessage = "Exchange rate must be a number between {1} and {2}.")]
我得到的信息是“字段汇率必须是......之间的数字”
我想摆脱“The field”这个词。什么是实现目标的最简单方法?
答案 0 :(得分:1)
以下对我有用。我收到了消息"汇率必须是介于0.001和9999之间的数字"。如果您发布了模型类的结构,那将会很有帮助。
<强> C#强>
using System.ComponentModel.DataAnnotations;
// ...
public class Foo
{
[Range(typeof(Decimal), "0.001", "9999", ErrorMessage = "Exchange rate must be a number between {1} and {2}.")]
[RegularExpression(@"\d+?(?:\.\d{3,3})?", ErrorMessage="Exchange rate must be a number.")]
[Required(ErrorMessage = "Exchange rate is required.")]
public decimal ExchangeRate { get; set; }
}
查看强>
@model WebApplication2.Models.Foo
@using (Html.BeginForm())
{
@Html.LabelFor(model => model.ExchangeRate)<br />
@Html.TextBoxFor(model => model.ExchangeRate)<br />
@Html.ValidationMessageFor(model => model.ExchangeRate)<br />
<button type="submit">Submit</button>
}
@section scripts
{
@* Assuming bundle is jqueryval *@
@Scripts.Render("~/bundles/jqueryval")
}
<强>控制器强>
public ActionResult Test()
{
return View(new Foo());
}
[HttpPost]
[ActionName("Test")]
public ActionResult TestConfirmed(Foo foo)
{
// NOTE: You would need additional logic for dealing with the ModelState.IsValid
// This is for illustration purposes only
return View(foo);
}