.net mvc数据注释模型状态返回始终为true

时间:2017-06-29 15:20:57

标签: asp.net-mvc data-annotations

当我发布一个无效的序列时,它设置为""(空字符串),我希望ModelState.isValid为false,但它返回true ..这是我的代码。

        private string _tcno { get; set; }  

        [Required(ErrorMessage = "Enter serial")]
        [StringLength(11, MinimumLength = 11, ErrorMessage="Invalid Serial Number")]
        [Column(TypeName = "nchar")]
        public string TCNO
        {
            get { return _tcno ?? ""; }
            set { 
                 value = value ?? ""; 
                 _tcno = value.IsValidTC() ? value : ""; 
            }
        }

我相信最小11长度验证为什么ModelState.isValid在这里是真的?

2 个答案:

答案 0 :(得分:0)

希望这会有所帮助。我做了以下工作,我得到了一个有效的'对于12345678901,我得到了无效的'为1234

查看:

@model Testy20161006.Controllers.AttributeViewModel
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>IndexValid10</title>
</head>
<body>
    <div>
        @using (Html.BeginForm())
        {
            @Html.TextBoxFor(r => r.TCNO);
            <input type="submit" value="submit" />
        }
    </div>
</body>
</html>

控制器/视图模型:

public class AttributeViewModel
{
    private string _tcno { get; set; }

    [Required(ErrorMessage = "Enter serial")]
    [StringLength(11, MinimumLength = 11, ErrorMessage = "Invalid Serial Number")]
    [Column(TypeName = "nchar")]
    public string TCNO
    {
        get { return _tcno ?? ""; }
        set
        {
            value = value ?? "";
            //modified this line
            _tcno = value;
        }
    }
}

public class HomeController : Controller
{
    [HttpPost]
    public ActionResult IndexValid10(AttributeViewModel attributeViewModel)
    {
        //set a breakpoint here
        if (ModelState.IsValid)
        {
            var isValid = true;
        }
        return View();
    }

答案 1 :(得分:0)

下面的Woking副本是使用我的验证方法,并设置' - '如果它的序列号无效,这种方式有效的错误信息就像我预期的那样。

<table class="table table-bordered">
    <thead>
    <tbody>
    <tr>
        <?php
        for($x=0; $x < $row['noof10s_vnr']; $x++){
        ?>
        <td><img id="image{{$x}}" alt="" class="yellow-process center-block " onclick="imageClick(<?php echo $row['id_vnr']; ?>)" name="<?php echo $row['id_vnr']; ?>" src="../../css/icons/vinyl-rolls/cut.png"></td>
        <?php
        }
        ?>

    </tr>
    </tbody>
</table>