“字符串未被识别为有效日期时间”

时间:2018-07-30 11:14:21

标签: c# model-view-controller

我正在使用Bootstrap datetimepicker,正在使用字符串类型的ViewModel('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>

3 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

尝试一下

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

答案 2 :(得分:0)

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

还可以设置系统日期时间格式