Search code examples
c#asp.net-mvcmodelstate

ModelState.IsValid always true


Visual Studio 2015 Update 1.
MVC 5.2.3.
.NET 4.5.2

It's picking up the Display Name ok, but it's not honoring the Required attribute, it would seem. Thanks!!!

View:

@model Insure.Entities.Policy

@{  ViewBag.Title = "Policy"; }

<h2>Policy</h2>

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

<div class="form-horizontal">
    <h4>Create</h4>
    <hr />
    @Html.ValidationSummary(true)

    <div class="form-group">
        @Html.LabelFor(model => model.EffDate, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.EffDate)
            @Html.ValidationMessageFor(model => model.EffDate)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.ExpDate, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.ExpDate)
            @Html.ValidationMessageFor(model => model.ExpDate)
        </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>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

Model:

using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Insure.Entities
{
public class Policy
{
    public int PolicyID { get; set; }
    public Guid PolicyNumber { get; set; }

    [Required(ErrorMessage = "Effective Date Required")]
    [DataType(DataType.DateTime)]
    [DisplayName("Effective Date")]
    public DateTime EffDate { get; set; }

    [Required(ErrorMessage = "Expiration Date Required")]
    [DataType(DataType.DateTime)]
    [DisplayName("Expiration Date")]
    public DateTime ExpDate { get; set; }
}
}

Controller:

    // POST: Policy/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(FormCollection collection)
    {
        try
        {
            if (ModelState.IsValid)
            {
                // TODO: Add logic to insert to DB
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }           
        }
        catch
        {
            return View();
        }
    }

Solution

  • public ActionResult Create(FormCollection collection) 
    

    should be

    public ActionResult Create(Policy myPolicyModel)
    

    Then validation will be executed on the model.