如何在StringLengthAttribute工作? [英] How does the StringLengthAttribute work?

查看:793
本文介绍了如何在StringLengthAttribute工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用验证实体框架和ASP.NET MVC3我的模型时,使用StringLengthAttribute遇到了麻烦。

I am having trouble using the StringLengthAttribute when validating my model using Entity Framework and ASP.NET MVC3.

我的模型是基于具有使用该MetadataType属性告诉MVC元数据搜索时使用哪种类型的部分类实体框架的实体。这显示在下面的code:

My model is based on an Entity Framework entity which has a partial class that uses the MetadataType attribute to tell the MVC which type to use when searching for metadata. This is shown in the code below:

[MetadataType(typeof(PartMetadata))]
public partial class Part { }

class PartMetadata
{
    [DisplayName("Part number")]
    [Required(ErrorMessage="* Required")]
    [StringLength(50, MinimumLength = 3, ErrorMessage = "* Part numbers must be between 3 and 50 character in length.")]
    public string Number { get; set; }

    [StringLength(255, MinimumLength=3,
        ErrorMessage="* Part descriptions must be between 3 and 255 characters in length.")]
    public string Description { get; set; }

    [DisplayName("Drawing required?")]
    public bool DrawingRequired { get; set; }
}

我遇到的问题是,描述字段没有正确验证。使用下面我的模型code被确认为OK,我重定向到我的控制器的索引页即使在描述字段为空。

The problem I am having is that the description field is not being validated properly. Using the code below my model is validated as OK and I am redirected to the Index page of my controller even when the description field is left blank.

if (ModelState.IsValid)
{
    return RedirectToAction("Index");
 }
 else
 {
     return View();
  }

如果我添加到RequiredAttribute标签描述字段,然后我的模型被归类为无效状态,我的形式显示重新加载所需要的属性的默认的错误消息。如果我随后编辑描述字段就说明我在字符串长度属性设置的验证错误消息。

If I add a RequiredAttribute to the description field then my model is classed as being in an invalid state and my form is reloaded showing the default error message of the required attribute. If I subsequently edit the description field then it shows the validation error message I have set in the string length attribute.

这是属性应该如何表现?这不是装饰与所需的属性性质的问题,但似乎领域不需要我只是想确保,如果用户不输入一些东西,然后它属于字符串长度属性的范围内常理。

Is this how the attribute should behave? It isn't a problem decorating the properties with the required attribute but seems counterintuitive as the field isn't required I just want to ensure that if the user does type something then it falls within the range of the string length attribute.

推荐答案

是的,这是正确的行为。 StringLength 验证字符串是一定的长度,但不的需要的字符串输入。装饰用[必填]描述,让你同时拥有了字符串要求,StringLength将提供关于字符串长度的限制。

Yes, that is the correct behavior. StringLength verifies that a string is a certain length, but does not REQUIRE that the string be entered. Decorate Description with [Required], so that you have both a requirement for the string, and StringLength will provide the constraints on the string length.

这篇关于如何在StringLengthAttribute工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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