【问题标题】:'String is not recognised as valid date time''字符串未被识别为有效日期时间'
【发布时间】:2018-07-30 11:14:21
【问题描述】:

我正在使用 Bootstrap datetimepicker,我在我的视图模型(“StartDate”和“EndDate”)中使用两个字段,它们是字符串类型,而在我的实体中是 Datetime 类型。当我转换成格式时..它给了我例外。

字符串未被识别为有效的日期时间。

我的视图模型类。

    [Required]
    public string Name { get; set; }

    [Required]
    public string RefNo{ get; set; }

    [Required]
    public int? PaxNo { get; set; }

    [Required]

    public string StartDate { get; set; }

    [Required]

    public string EndDate { get; set; }

    [Required]
    [Display(Name = "StartCity")]
    public string StartCityId { get; set; }

我的实体类

    [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public int UserId { get; set; }

    public string Name { get; set; }

    public  string RefernceNo { get; set; }

    public int PaxNo { get; set; }

    public DateTime StartDate { get; set; }

    public DateTime EndDate { get; set; }

    public int StartCityId { get; set; }

控制器:- PostMethod

[HttpPost]
        public ActionResult AddTour(TourViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var loginUserId = User.Identity.GetUserId<int>();
                    model.Cities = _cityRepository.GetCities();
                    model.Coaches = GetCoaches();

                    var startDate = Convert.ToDateTime(Convert.ToDateTime(model.StartDate).ToString("yyyy/MM/dd"));

                    var endDate = Convert.ToDateTime(Convert.ToDateTime(model.EndDate).ToString("yyyy/MM/dd"));
                    var tour = new Tour()
                    {
                        Name = model.Name,
                        RefernceNo = model.RefNo,
                        PaxNo = model.PaxNo ?? 0,
                        StartDate = Convert.ToDateTime(model.StartDate.ToString()),
                        EndDate = Convert.ToDateTime(model.EndDate.ToString()),
                        StartCityId = int.Parse(model.StartCityId),
                        EndCityId = int.Parse(model.EndCityId),
                        Opeartor = model.Operator,
                        Note = model.Note,
                        CoachId = int.Parse(model.CoachId),
                        StatusId = int.Parse(model.StatusId),
                        CreatedDate = DateTime.Now,
                        UserId=loginUserId,
                        CreatedBy = loginUserId,

                    };
                    // add record to database
                    _tourRepository.Add(tour);
                    TempData["SuccessMessage"] = "Tour Added Successfully";
                    return RedirectToAction("AddTour");
                }
                catch(Exception ex)
                {
                    TempData["ErrorMessage"] = " Something went wrong.Please try again";
                    return RedirectToAction("AddTour");
                }
            }
            else
            {
                TempData["ErrorMessage"] = " Something went wrong.Please try again";
                return RedirectToAction("AddTour");
            }
        }

我的看法

<div class="form-group">
    @Html.LabelFor(model => model.StartDate, htmlAttributes: new { @class = "control-label col-md-1"  })
    <div class="col-md-10">
        @Html.TextBoxFor(m => m.StartDate, Model != null && Model.StartDate != null ? string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:yyyy/MM/dd}", Model.StartDate) : "", new { @placeholder = "Enter Start Date", @class = "form-control date" } )
        @Html.ValidationMessageFor(model => model.StartDate, "", new { @class = "text-danger" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.EndDate, htmlAttributes: new { @class = "control-label col-md-1" })
    <div class="col-md-10">
        @Html.TextBoxFor(m => m.EndDate, Model != null && Model.EndDate != null ? string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:yyyy/MM/dd}", Model.EndDate) : "", new { @placeholder = "Enter End Date", @class = "form-control date", onblur = "compare();" })
        @Html.ValidationMessageFor(model => model.EndDate, "", new { @class = "text-danger", @id = "errormsg"})
    </div>
</div>

【问题讨论】:

  • 异常存在是有原因的。它们被抛出在它们发生的行项目上(附加调试器以查看此操作)并且它们(通常)具有描述性消息。在这种情况下,错误会告诉您到底出了什么问题,您不能将 DateTime 分配给字符串。这应该使您得出结论,即需要更改分配的一侧,因此将目标更改为 DateTime 或更改分配给字符串的值。在这种情况下,前者将是更正确的解决方案。
  • 我尝试了一切,在 DateTime 或 Convert.toDatetime 中使用了字段..但没有解决这个错误..请检查我的代码一次,我可以做些什么来改变它
  • [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")] [DataType(DataType.Date)] 在你的模型上试试这个数据注释
  • @avi DateTime 没有格式,它是一个二进制值。格式仅在将日期呈现为字符串时使用。 Convert.ToDateTime(Convert.ToDateTime(model.StartDate).ToString("yyyy/MM/dd")) 最终没有意义,运气好的话,它会以某种方式产生 original DateTime. If you want to display a DateTime` 属性,在DisplayFormat 属性中指定格式或在HTML 助手
  • @PanagiotisKanavos,我什至尝试过 DisplayFormat..但什么也没发生

标签: c# model-view-controller


【解决方案1】:

这将取决于定义的 System.Globalization.Cultureinfo.Currentculture 您应该确保格式与从前端输入的文本兼容。

还要准备好管理可能的转换错误(javascript 中的所有验证都应在后端重复)

如果您将 StartDate 和 EndDate 声明为 DateTime,则无需在控制器主体中进行强制转换

【讨论】:

    【解决方案2】:

    试试这个

    StartDate = DateTime.ParseExact(model.StartDate, "yyyy/M/d", new CultureInfo("en-US"));
    EndDate = DateTime.ParseExact(model.EndDate, "yyyy/M/d", new CultureInfo("en-US"));
    

    【讨论】:

      【解决方案3】:

      [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")] [DataType(DataType.Date)]

      同时设置你的系统日期时间格式

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-24
        • 1970-01-01
        • 1970-01-01
        • 2013-02-07
        • 2011-10-21
        • 2017-08-03
        • 1970-01-01
        相关资源
        最近更新 更多