ASP.NET MVC:DataAnnotations - 显示表明一个字段必须是数字的错误信息 [英] ASP.NET MVC: DataAnnotations - Show an error message indicating that a field must be numeric

查看:2039
本文介绍了ASP.NET MVC:DataAnnotations - 显示表明一个字段必须是数字的错误信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎有一个洞的方式DataAnnotations一些工作在一个用户进入一些文本字段,将进入一个int不会到达DataAnnotations code。它揭开序幕的模型绑定错误,并显示错误给用户的值'一'是无效的XXXX领域。

总之,这一切都非常不错,它会自动处理这种情况,但其实我是想显示指示问题如错误消息。 值'一'不是数字,请为XXXX场数值输入

我已经尝试列出<一个解决方案href=\"http://stackoverflow.com/questions/1538873/how-to-replace-the-default-modelstate-error-message-in-asp-net-mvc-2\">http://stackoverflow.com/questions/1538873/how-to-replace-the-default-modelstate-error-message-in-asp-net-mvc-2和<一个href=\"http://stackoverflow.com/questions/646270/asp-net-mvc-custom-validation-message-for-value-types/1374653#1374653\">http://stackoverflow.com/questions/646270/asp-net-mvc-custom-validation-message-for-value-types/1374653#1374653,但我不能让他们的工作。

看来,我的资源文件没有被读取可言,因为这里(http://msdn.microsoft.com/en-us/library/system.web.mvc.defaultmodelbinder.resourceclasskey.aspx)它规定如果该属性设置为无效类键(如不存在的资源文件),MVC抛出一个异常。即使我改线DefaultModelBinder.ResourceClassKey =asdfasdhfk没有例外。

任何人有什么想法?

编辑:下面是一些code。所有的它正在减去我Messages.resx文件的消息不被使用。在code为Messages.resx是产生这样的汽车,我将不包括它。

所以,进入一到一个通用的消息ProcessOrder结果,而不是什么我已经进入Messages.resx为PropertyValueInvalid(和InvalidPropertyValue好措施)。

Application_Start方法中

 保护无效的Application_Start()
{
    的RegisterRoutes(RouteTable.Routes);
    ModelBinders.Binders.DefaultBinder =新Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder(); //要使用一套dataanooations
    DefaultModelBinder.ResourceClassKey =消息; //设置数据注解,看在messages.resx默认邮件
    ValidationExtensions.ResourceClassKey =消息;
}

实体类

  [MetadataType(typeof运算(GLMetaData))]
公共部分类GL
{}公共类GLMetaData
{
    公众诠释TransRefId {搞定;组; }    [显示名称(处理订单)]
    公众诠释? ProcessOrder {搞定;组; }    [显示名称(跨类型)
    [StringLength(50)]
    公共字符串TransType {搞定;组; }    [StringLength(100)]
    公共字符串描述{搞定;组; }    [显示名称(GL code)]
    [StringLength(20)]
    公共字符串GL code {搞定;组; }    [显示名称(代理商信用否)]
    [StringLength(50)]
    公共字符串AgentsCreditNo {搞定;组; }    [需要]
    公共BOOL活跃{搞定;组; }
}

控制器动作:

 的[AcceptVerbs(HttpVerbs.Post)
    公众的ActionResult编辑(GL glToBeUpdated)
    {
        尝试
        {
            如果(!ModelState.IsValid)
                返回查看(glToBeUpdated);            //设置自动属性
            glToBeUpdated.UpdateDate = DateTime.Now;
            glToBeUpdated.UpdateUser = this.CurrentUser;            glDataLayer.update(glToBeUpdated);            glDataLayer.submitChanges();            返回RedirectToAction(「指数」);
        }
        抓住
        {
            glDataLayer.abortChanges();            扔;
        }
    }


解决方案

我也打击了类似的问题是什么来清除模型状态,验证对的ModelState [XXXX。Value.AttemptedValue ,而不是对所造成的试图把无效值进入模型的财产,填充错误信息并重置模型值调零值。

这样我可以有我想要的错误消息,并在必要时提供不止一个(一个值是必需的或值必须是数字)。

There appears to be something of a hole in the way DataAnnotations works in that a user entering in some text into a field that will go into an int will never reach the DataAnnotations code. It kicks off a model binding error and displays the error to the user "The value 'a' is not valid for the XXXX field."

Anyway, it's all very nice that it automatically handles this situation, but I actually want to display an error message indicating the problem eg. "The value 'a' is not numeric. Please enter in a numeric value for the XXXX field".

I have tried the solutions set out http://stackoverflow.com/questions/1538873/how-to-replace-the-default-modelstate-error-message-in-asp-net-mvc-2 and http://stackoverflow.com/questions/646270/asp-net-mvc-custom-validation-message-for-value-types/1374653#1374653, but I can't get them to work.

It appears that my resource file is not being read at all, since here (http://msdn.microsoft.com/en-us/library/system.web.mvc.defaultmodelbinder.resourceclasskey.aspx) it states "If the property is set to an invalid class key (such as a resource file that does not exist), MVC throws an exception." and even if I change the line to DefaultModelBinder.ResourceClassKey = "asdfasdhfk" there is no exception.

Anyone have any ideas?

EDIT: Here is some code. All of it is working minus my Messages.resx file's messages are not being used. The code for Messages.resx is auto generated so I won't include it.

So entering "a" into ProcessOrder results in a generic message rather than what I have entered into Messages.resx for PropertyValueInvalid (and InvalidPropertyValue for good measure).

Application_Start method

protected void Application_Start()
{            
    RegisterRoutes(RouteTable.Routes);
    ModelBinders.Binders.DefaultBinder = new Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder(); //set dataanooations to be used
    DefaultModelBinder.ResourceClassKey = "Messages"; //set data annotations to look in messages.resx for the default messages
    ValidationExtensions.ResourceClassKey = "Messages";
}

Entity Class

[MetadataType(typeof(GLMetaData))]
public partial class GL
{

}



public class GLMetaData
{
    public int TransRefId { get; set; }

    [DisplayName("Process Order")]
    public int? ProcessOrder { get; set; }

    [DisplayName("Trans Type")]
    [StringLength(50)]
    public string TransType { get; set; }

    [StringLength(100)]
    public string Description { get; set; }

    [DisplayName("GL Code")]
    [StringLength(20)]
    public string GLCode { get; set; }

    [DisplayName("Agents Credit No")]
    [StringLength(50)]
    public string AgentsCreditNo { get; set; }

    [Required]
    public bool Active { get; set; }
}

Controller Action:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(GL glToBeUpdated)
    {
        try
        {
            if (!ModelState.IsValid)
                return View(glToBeUpdated);

            //set auto properties
            glToBeUpdated.UpdateDate = DateTime.Now;
            glToBeUpdated.UpdateUser = this.CurrentUser;

            glDataLayer.update(glToBeUpdated);

            glDataLayer.submitChanges();

            return RedirectToAction("Index");
        }
        catch
        {
            glDataLayer.abortChanges();

            throw;
        }
    }

解决方案

What I did to combat a similar issue was to clear the model state, validate against ModelState["XXXX"].Value.AttemptedValue instead of against the nulled value caused by an trying to put an invalid value into the Model's property, populating the error messages and resetting the Model values.

That way I can have the error messages I want and if necessary offer more than one ("a value is required" or "the value must be numeric").

这篇关于ASP.NET MVC:DataAnnotations - 显示表明一个字段必须是数字的错误信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆