Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net core 使用StringLength验证属性进行模型验证_Asp.net Core_Model Validation - Fatal编程技术网

Asp.net core 使用StringLength验证属性进行模型验证

Asp.net core 使用StringLength验证属性进行模型验证,asp.net-core,model-validation,Asp.net Core,Model Validation,在我的ASP.NET MVC Core 1.1.1中,我有一个表单,其中一个输入如下,其中用户需要输入两个字符的区号,如01、02、…10、11等。但是当我通过输入区号(如123)提交表单时,它仍然成功提交表单,而不强制用户输入两个字符的区号。我可能错过了什么 MyViewModels ... [Display(Name = "District"),StringLength(2)] public string Dist { get; set; } ... 表格 @model MyProj.Mo

在我的ASP.NET MVC Core 1.1.1中,我有一个表单,其中一个输入如下,其中用户需要输入两个字符的区号,如01、02、…10、11等。但是当我通过输入区号(如123)提交表单时,它仍然成功提交表单,而不强制用户输入两个字符的区号。我可能错过了什么

MyViewModels

...
[Display(Name = "District"),StringLength(2)]
public string Dist { get; set; }
...
表格

@model MyProj.Models.MyViewModel
...
<div class="form-group">
    <label asp-for="Dist" class="col-md-2 control-label"></label>
    <div class="col-md-2">
        <input asp-for="Dist" class="form-control" />
        <span asp-validation-for="Dist" class="text-danger"></span>
    </div>
    <div class="col-sm-pull-8">01 to 53 — district codes</div>
</div>
...
@model MyProj.Models.MyViewModel
...
01至53-地区代码
...
注意
我正在使用最新版本的VS2017的默认
ASP.NET核心Web应用程序
模板,默认情况下,在使用该模板时安装必要的引导和其他Java脚本。

1-StringLength的第一个参数是最大长度。要定义最小值,您可以执行以下操作:

    [Display(Name = "District")]
    [Required]
    [StringLength(2, MinimumLength = 2)]
    public string Dist { get; set; }
或:

  • 缺少必需的属性 查看

    验证脚本:

    @section Scripts { @Html.Partial("_ValidationScriptsPartial") }
    
    控制器

    [HttpPost]
        public IActionResult Contact(MyViewModel model)
        {
            if (ModelState.IsValid)
            { ... }
    

    您是否添加了用于验证的客户端javascript?尝试检查服务器(操作)中的ModelState是否有效,如果无效,则检查原因是否是Dist属性,如果它说它无效,结果是您没有在客户端进行验证(javascript)@dime2lo我在上面的帖子中添加了一个注释来回答您的问题,其他读者可能也会问。您是否检查了模型是如何到达服务器的(如果ModelState有效)?如果是无效的,那么问题就出在客户机上。也许我错了,但是您必须添加javascript客户端验证部分
    @section Scripts{@{await Html.RenderPartialAsync(“_validationScripttial”);}
    如何注册MVC中间件(
    .AddMvc
    .AddMvcCore
    )。我问的原因是MVC数据注释服务应该注册,并且这只能通过
    AddMVC
    自动完成,否则您需要直接调用
    AddMvcCore().AddDataAnnotations()
    。请参阅
    StartUp.cs
    has
    AddMvc()中的@Set
    ConfigureServices(…)
    在其中。
    [HttpPost]
        public IActionResult Contact(MyViewModel model)
        {
            if (ModelState.IsValid)
            { ... }