在mvc中自定义错误消息

时间:2014-05-30 12:50:46

标签: asp.net-mvc

我在MVC 4.0中使用DataAnnotations验证,我有如下属性:

 [Range(typeof(Decimal), "0.001", "9999", ErrorMessage = "Exchange rate must be a number between {1} and {2}.")]

我得到的信息是“字段汇率必须是......之间的数字”

我想摆脱“The field”这个词。什么是实现目标的最简单方法?

1 个答案:

答案 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);
}