jjzjj

c# - 尽管具有相同代码的字段工作正常(在 C# MVC、ASP.Net Core 中),但 DateTime 验证不起作用

coder 2024-05-31 原文

编辑 1

只是澄清几点,

  • 日期时间选择器/脚本似乎工作正常,时间和日期是可选的,并按预期使用正确的值填充文本框。
  • 当用户在文本框中手动输入时间/日期并输入无效时间(即“78/5/2017 12:00”或“12/5/2017 12:62”)时会出现此问题
  • 我已经更新了代码中的拼写错误,错误仍然出现在更正后的代码中。

我祈祷我错过了一些明显的东西,因为这对我来说毫无意义。您能提供的任何帮助将不胜感激。我在问题的末尾包含了我的代码。

问题

  • 我有两个 DateTime 字段,它们包含在我的应用程序页面的表单中:StartTimeEndTime
  • 这两个字段都使用(我认为是)相同的代码设置并放到页面上。
  • StartTime 字段工作得很好,只是输入的有效时间除外,并在用户更正之前显示无意义时间(例如 28:30 或 17:67)的错误。
  • EndTime 字段没有正确验证。错误的输入在传回 Controller 之前会切换回当前的时间/日期, Controller 甚至看不到错误的值,这意味着我无法捕捉到它并在此时返回错误。
  • 如果在两个字段中都给出了无意义的值,则提交将被阻止,并且两个字段都会显示验证错误,这表明 EndTime 验证确实有效,它只是不会阻止表单提交。

我的努力

因为我有一个工作领域,所以我试图用它来纠正错误。然而,我在意识到两者之间没有区别时遇到了绊脚石。确定我一定错过了一些东西,我改变了变量名,以便 StartTime 将使用 EndTime 代码,反之亦然,我在下面的每个部分中都这样做了一个接一个地希望找到一个正在工作的领域交换的点。然而,那从未发生过。即使他们的全部代码都已切换,仍然发现 EndTime 变量/字段已损坏,而 StartTime 变量/字段仍在工作。

我的研究

尽管我花了将近一个星期的时间来处理这个错误,但现在我无法在网上找到任何类似的问题,并且完全不知道该去哪里或现在尝试什么。我曾尝试寻找由 DateTime 日历选择器引起的问题以及一般的验证错误,但找不到任何对这种情况有用的东西。

这是项目完成前要修复的最后一个错误之一,因此您能提供的任何帮助甚至想法都将是非常棒的。

代码

我已经将我能想到的与相关字段交互的所有内容都包含在此处。如果我遗漏了什么或者您需要更多信息,请告诉我。

实体模型

我的 Record 实体中有以下两个 DateTime 字段

public partial class Record
{
    // Other entity fields
    // ....
    // ...
    // ..

    [DisplayName("Start Time")]
    [DataType(DataType.DateTime)]
    [DisplayFormat(DataFormatString = "{0:g}", ApplyFormatInEditMode = true)]
    public DateTime StartTime { get; set; }

    [DisplayName("End Time")]
    [DataType(DataType.DateTime)]
    [DisplayFormat(DataFormatString = "{0:g}", ApplyFormatInEditMode = true)]
    public DateTime EndTime { get; set; }

    // and in the constructor
    public Record()
    {
        // initialise the DateTime fields with the current DateTime,
        // adjusted for daylight savings

        BaseController b = new BaseController();
        StartTime = b.TimeNow();
        EndTime = b.TimeNow();
    }
}

为了完成,这是 TimeNow() 函数的代码:

public DateTime TimeNow()
{
    TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
    DateTime t = DateTime.Now;
        
    if (tz.IsDaylightSavingTime(t))
        t = t.AddHours(1);

    return t;
}

View 模型

Record 实体随后被包含到 ViewModel 中,如下所示:

public class Home_UserAddRecord
{
    [DisplayName("Record")]
    public Record record { get; set; }

    // Other ViewModel fields
    // ....
    // ...
    // ..

    // and the blank constructor:
    public Home_UserAddRecord()
    {
        record = new Record();
        Error = false;
        ErrorMessage = string.Empty;
    }
}

CSHTML 表单

然后将它们包含在页面上的表单中,如下所示:

@using (Html.BeginForm())
{
    <div class="form-horizontal">

        <div class="form-group col-md-12">
            @Html.LabelFor(model => model.record.StartTime, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-5">
                @Html.EditorFor(model => model.record.StartTime, new { htmlAttributes = new { @Value = Model.record.StartTime.ToString("dd/MM/yyyy HH:mm"), @class = "form-control", @id = "StartDate" } })
                @Html.ValidationMessageFor(model => model.record.StartTime, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group col-md-12">
            @Html.LabelFor(model => model.record.EndTime, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-5">
                @Html.EditorFor(model => model.record.EndTime, new{ htmlAttributes = new{ @Value = Model.record.EndTime.ToString("dd/MM/yyyy HH:mm"), @class = "form-control", @id = "EndDate" } })
                @Html.ValidationMessageFor(model => model.record.EndTime, "", new { @class = "text-danger" })
            </div>
        </div>

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

    </div>
}

附加脚本

最后,他们应用了一个脚本,以允许在每个输入上使用日历选择器。脚本如下所示:

@section Scripts{

    <script>

        var Start = new dhtmlXCalendarObject("StartDate");
        Start.setDateFormat("%d/%m/%Y %H:%i");
        Start.showToday();
        Start.attachEvent("onTimeChange", function (d) {
            var DateText = Start.getDate(true)
            document.getElementById("StartDate").value = DateText;
        });


        var End = new dhtmlXCalendarObject("EndDate");
        End.setDateFormat("%d/%m/%Y %H:%i");
        End.showToday();
        End.attachEvent("onTimeChange", function (d) {
            var DateText = End.getDate(true)
            document.getElementById("EndDate").value = DateText;
        });

    </script>
}

最佳答案

也许建议使用 DateTime.TryParseExact 方法,该方法将使用您所需的格式验证日期的“字符串”表示形式,并在字符串不符合您指定的格式时返回错误。这是代码,注意日期格式基于澳大利亚标准日期。您当然也可以为此添加小时和分钟。

注意 parsedDate 是一种 DateTime 格式。下面的用法是:

public void test(){
   DateTime ParsedDate;
   string SomeDate = "12-May-2017";
   if(parseDate(SomeDate, out ParsedDate))
   {
       // Date was parsed successfully, you can now used ParsedDate, e.g.
       Customer.Orders[0].DateRequired = ParsedDate;
   }
   else
   {
    // Throw an error
   }
}

还有方法声明。在静态类中使用,或直接在您的类中使用。

public static bool parseDate(string theDate, out DateTime parsedDate)
        {
            string[] dateFormats = { "d-M-yy", "d-MMM-yy", "d-MMM-yyyy", "d-M-yyyy", "d/M/yy", "d/M/yyyy", "yyyy-mm-dd" };
            bool result = DateTime.TryParseExact(
                theDate,
                dateFormats,
                new CultureInfo("en-AU"),
                DateTimeStyles.None, out parsedDate);

            return result;
        } //Convert string-based date to DateTime.  Uses a variety of parse templates 

关于c# - 尽管具有相同代码的字段工作正常(在 C# MVC、ASP.Net Core 中),但 DateTime 验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44000296/

有关c# - 尽管具有相同代码的字段工作正常(在 C# MVC、ASP.Net Core 中),但 DateTime 验证不起作用的更多相关文章

  1. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  2. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  3. ruby-on-rails - Rails 源代码 : initialize hash in a weird way? - 2

    在rails源中:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb可以看到以下内容@load_hooks=Hash.new{|h,k|h[k]=[]}在IRB中,它只是初始化一个空哈希。和做有什么区别@load_hooks=Hash.new 最佳答案 查看rubydocumentationforHashnew→new_hashclicktotogglesourcenew(obj)→new_has

  4. ruby-on-rails - Rails 3 I18 : translation missing: da. datetime.distance_in_words.about_x_hours - 2

    我看到这个错误:translationmissing:da.datetime.distance_in_words.about_x_hours我的语言环境文件:http://pastie.org/2944890我的看法:我已将其添加到我的application.rb中:config.i18n.load_path+=Dir[Rails.root.join('my','locales','*.{rb,yml}').to_s]config.i18n.default_locale=:da如果我删除I18配置,帮助程序会处理英语。更新:我在config/enviorments/devolpment

  5. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  6. ruby-on-rails - 浏览 Ruby 源代码 - 2

    我的主要目标是能够完全理解我正在使用的库/gem。我尝试在Github上从头到尾阅读源代码,但这真的很难。我认为更有趣、更温和的踏脚石就是在使用时阅读每个库/gem方法的源代码。例如,我想知道RubyonRails中的redirect_to方法是如何工作的:如何查找redirect_to方法的源代码?我知道在pry中我可以执行类似show-methodmethod的操作,但我如何才能对Rails框架中的方法执行此操作?您对我如何更好地理解Gem及其API有什么建议吗?仅仅阅读源代码似乎真的很难,尤其是对于框架。谢谢! 最佳答案 Ru

  7. ruby - 模块嵌套代码风格偏好 - 2

    我的假设是moduleAmoduleBendend和moduleA::Bend是一样的。我能够从thisblog找到解决方案,thisSOthread和andthisSOthread.为什么以及什么时候应该更喜欢紧凑语法A::B而不是另一个,因为它显然有一个缺点?我有一种直觉,它可能与性能有关,因为在更多命名空间中查找常量需要更多计算。但是我无法通过对普通类进行基准测试来验证这一点。 最佳答案 这两种写作方法经常被混淆。首先要说的是,据我所知,没有可衡量的性能差异。(在下面的书面示例中不断查找)最明显的区别,可能也是最著名的,是你的

  8. ruby - 寻找通过阅读代码确定编程语言的ruby gem? - 2

    几个月前,我读了一篇关于ruby​​gem的博客文章,它可以通过阅读代码本身来确定编程语言。对于我的生活,我不记得博客或gem的名称。谷歌搜索“ruby编程语言猜测”及其变体也无济于事。有人碰巧知道相关gem的名称吗? 最佳答案 是这个吗:http://github.com/chrislo/sourceclassifier/tree/master 关于ruby-寻找通过阅读代码确定编程语言的rubygem?,我们在StackOverflow上找到一个类似的问题:

  9. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

  10. C# 到 Ruby sha1 base64 编码 - 2

    我正在尝试在Ruby中复制Convert.ToBase64String()行为。这是我的C#代码:varsha1=newSHA1CryptoServiceProvider();varpasswordBytes=Encoding.UTF8.GetBytes("password");varpasswordHash=sha1.ComputeHash(passwordBytes);returnConvert.ToBase64String(passwordHash);//returns"W6ph5Mm5Pz8GgiULbPgzG37mj9g="当我在Ruby中尝试同样的事情时,我得到了相同sha

随机推荐