MVC范围属性无法正常工作

时间:2014-01-09 15:25:15

标签: asp.net-mvc asp.net-mvc-4 datetime

我有一个RangeAttribute来检查数据字段的值是否在这里的指定值范围内,即使我在“01/01/2000”之间选择一个日期,也会给我一个验证错误, “2015年1月1日”

 [Range(typeof(DateTime), "01/01/2000", "01/01/2015")]
 [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
 [DataType(DataType.Date)]
 public Nullable<System.DateTime> Date { get; set; }

这是我的edit.cshtml代码:

@model StringLength.Models.Employee

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

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

<fieldset>
    <legend>Employee</legend>

    @Html.HiddenFor(model => model.ID)

    <div class="editor-label">
        @Html.LabelFor(model => model.Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Gender)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Gender)
        @Html.ValidationMessageFor(model => model.Gender)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Email)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Email)
        @Html.ValidationMessageFor(model => model.Email)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Age)
        @Html.ValidationMessageFor(model => model.Age)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Date)
        @Html.ValidationMessageFor(model => model.Date)
    </div>

    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>
}

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

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

例如,如果我选择1.1.2014,我不应该看到任何验证错误。 有人可以帮忙吗? 提前致谢! enter image description here

2 个答案:

答案 0 :(得分:1)

首先,DateTime结构未能从给定的字符串中正确创建。由于您的消息为红色,表示这些字符串已转换为1.1.1910和1.1.2060 DateTime s。你应该使用CustomValidation attribute

其次,在服务器端将01.01.2014转换为DateTime可能会出现问题。请记住,您可能正在使用在转换和绑定中发挥作用的特定文化。

答案 1 :(得分:0)

要解决此问题,我们可以创建自定义DateRangeAttribute。这是步骤 1.右键单击解决方案资源管理器中的项目名称,然后添加“Common”文件夹。 2.右键单击“Common”文件夹,然后添加名为DateRangeAttribute.cs的类文件 3.将以下代码复制并粘贴到DateRangeAttribute.cs类文件中。

using System;
using System.ComponentModel.DataAnnotations;

namespace MVCDemo.Common
{
    public class DateRangeAttribute : RangeAttribute
    {
        public DateRangeAttribute(string minimumValue)
            : base(typeof(DateTime), minimumValue, DateTime.Now.ToShortDateString())
        {

        }
    }
}
  1. 最后使用我们的自定义DateRangeAttribute修饰“HireDate”属性,如下所示。请注意,我们只传递最小日期值。最大日期值将是今天的日期。请注意,DateRangeAttribute存在于MVCDemo.Common命名空间中。

    [DATERANGE( “01/01/2000”)] [DisplayFormat(DataFormatString =“{0:d}”,ApplyFormatInEditMode = true)] public DateTime HireDate {get;组; }

相关问题