asp.net数据注释字段的长度 [英] asp.net data annotations field length

查看:50
本文介绍了asp.net数据注释字段的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在字段上有以下数据注释

I currently have the following data annotation on a field

[StringLength(1000, MinimumLength = 6, ErrorMessage = "field must be atleast 6 characters")]
public string myField {get;set;}

我是否可以更改数据注释,使其仅在用户在字段中键入内容时才起作用?换句话说,可以将该字段保留为空,但是如果用户在该字段中键入一个值,则其长度应在6-1000个字符之间.

Can I change the data annotation such that it works only if the user types something in the field? In other words, it is okay to leave the field empty but if the user types a value in the field, it should be between 6-1000 characters in length.

推荐答案

StringLength属性已经是这种情况.如果您将该字段留空,则该模型将有效.你甚至都没有尝试过吗?

That's already the case with the StringLength attribute. If you leave the field empty the model will be valid. Didn't you even try this out?

型号:

public class MyViewModel
{
    [StringLength(1000, MinimumLength = 6, ErrorMessage = "field must be atleast 6 characters")]
    public string MyField { get; set; }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

查看:

@model MyViewModel

@using (Html.BeginForm())
{ 
    @Html.EditorFor(x => x.MyField)
    @Html.ValidationMessageFor(x => x.MyField)
    <button type="submit">OK</button>
}

您可以将该字段留空,并且不会收到验证错误.

You could leave the field empty and you won't get a validation error.

这篇关于asp.net数据注释字段的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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