尽管值正确,但行为奇怪,模型无效

时间:2017-12-11 08:06:04

标签: asp.net-mvc validation model

我正在使用Visual Studio 2017开发基于ASP.NET MVC 5的测试应用程序。

如果我在ASSORTCAT字段中提供值,则会显示The Value 'test' is invalid.

如果我在ASSORTCAT字段中提供空字符串,则ModelState.IsValidtrue,并在此后的第一行产生明显错误。

为什么会这样?

模型

public class Assortcat
{
    [Key]
    public int ID { get; set; }

    [Display(Name = "Cat")]
    [Required(ErrorMessage = "Cat can not be empty.")]
    [StringLength(50)]
    public string ASSORTCAT { get; set; }

    [ScaffoldColumn(false)]
    public DateTime CREATE_TIMESTAMP { get; set; }
    [ScaffoldColumn(false)]
    public DateTime LAST_EDIT_TIMESTAMP { get; set; }
}

控制器创建方法

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ASSORTCAT")] Assortcat assortcat)
    {
        if (ModelState.IsValid)
        {
            assortcat.ASSORTCAT = assortcat.ASSORTCAT.ToUpper();
            assortcat.CREATE_TIMESTAMP = DateTime.Now;
            assortcat.LAST_EDIT_TIMESTAMP = DateTime.Now;
            db.Assortcats.Add(assortcat);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(assortcat);
    }

创建视图

@using (Html.BeginForm()) 
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Assortcat</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.ASSORTCAT, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.ASSORTCAT, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.ASSORTCAT, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>

}

0 个答案:

没有答案