【发布时间】: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"))最终没有意义,运气好的话,它会以某种方式产生 originalDateTime. If you want to display aDateTime` 属性,在DisplayFormat属性中指定格式或在HTML 助手 -
@PanagiotisKanavos,我什至尝试过 DisplayFormat..但什么也没发生