0

I am developing a test application based on ASP.NET MVC 5 with Visual Studio 2017.

If I provide value in ASSORTCAT field, it says The Value 'test' is invalid.

If I provide empty string in ASSORTCAT field, ModelState.IsValid is true and it generates obvious error on the very first line after that.

Why is this happening?

Model

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; }
}

Controller Create Method

[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);
    }

Create View

@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>

}

Hemal
  • 3,682
  • 1
  • 23
  • 54

0 Answers0