ModelState.IsValid始终为true

时间:2016-03-22 19:00:21

标签: c# asp.net-mvc modelstate

Visual Studio 2015更新1.
MVC 5.2.3。
.NET 4.5.2

它正在拿起显示名称确定,但它似乎并不尊重必需属性。感谢!!!

查看:

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

型号:

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

控制器:

    // 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();
        }
    }

1 个答案:

答案 0 :(得分:2)

public ActionResult Create(FormCollection collection) 

应该是

public ActionResult Create(Policy myPolicyModel)

然后将对模型执行验证。