如何做到整模型验证在asp.net MVC 2 [英] How to do Integer model validation in asp.net mvc 2

查看:174
本文介绍了如何做到整模型验证在asp.net MVC 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个登记表,用户必须输入他们的房子面积有多大。我想这个值只是一个整数。有没有一种方法使用属性asp.net mvc的验证这个值?

I have a registration form and the user must enter the square footage of their house. I would like this value to be only an integer. Is there a way to validate this value using attributes asp.net mvc?

推荐答案

是的,它是,但你必须让你想要创建对象的平面版本,因为属性验证只运行后MVC有转换你的数据到模型中。其中,当你的价值是一个int,将无法验证,如果用户没有输入一个int,你会在你的ErrorMessage代替得到一个MVC的错误消息。

yes, it is, but you will have to make a flat version of the object you are wanting to create, because the validation with attributes only runs AFTER MVC has converted your data into the model. which, when your value is an int, will fail to validate if the user did not enter an int, and you will get a MVC error message in stead of your errormessage.

您可以发表你是想使对象?

can you post the object you are wanting to make?

有一台版我的意思是所有的日期时间和int的数据是在平坦的版本蜇伤。

with a flat version i mean all datetimes and ints are stings in the flat version.

然后我用这个:

    [DisplayName("Square meters")]
    [PosNumberNoZero(ErrorMessage = "need a positive number, bigger than 0")]
    public string squaremeters { get; set; }

在同一文件

public class PosNumberNoZeroAttribute : ValidationAttribute {
    public override bool IsValid(object value) {
        if (value == null) {
            return true;
        }
        int getal;
        if (int.TryParse(value.ToString(), out getal)) {

            if (getal == 0)
                return false;

            if (getal > 0)
                return true;
        }
        return false;

    }
}

如果我的ModelState是有效的话,我用AutoMapper我FlatModel转换成我的模型,这仅仅是2 code线。

if my modelstate is valid then, i use AutoMapper to convert my FlatModel into my Model, which is just 2 lines of code.

编辑:如果0是一个有效的数字:

edit: if 0 is a valid number:

public class PosNumberAttribute : ValidationAttribute {
    public override bool IsValid(object value) {
        if (value == null) {
            return true;
        }
        int getal;
        if (int.TryParse(value.ToString(), out getal)) {

            if (getal >= 0)
                return true;
        }
        return false;
    }
}

这篇关于如何做到整模型验证在asp.net MVC 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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