ASP.NET Entity Framework DateTime 始终设置为 01-01-00001

ASP.NET Entity Framework DateTime always set to 01-01-00001

提问人:Luigicr95 提问时间:1/26/2023 最后编辑:Luigicr95 更新时间:1/26/2023 访问量:140

问:

根据标题,我在 asp.net 中的日期选择器有问题:每次我尝试设置日期时,它总是在控制器上显示为“01-01-0001”。 这是我的观点(这是一个编辑,所以我更改了输入中的格式,否则从数据库中获取的日期不会显示):

<div class="form-group">
            @Html.LabelFor(model => model.ExamDate, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @*RIVEDERE INPUT DATA IN EDIT EXAM*@
                @*@Html.TextBoxFor(model => model.ExamDate, "{0:dd/MM/yyyy}", new {@type = "date", @value = Model.ExamDate.ToString("yyyy-MM-dd")})*@
                <input id="ExamDate" type="date" value="@Model.ExamDate.ToString("yyyy-MM-dd")" />
                @Html.ValidationMessageFor(model => model.ExamDate, "", new { @class = "text-danger" })
            </div>
        </div>

这是控制器:

        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Exams exams = db.Exams.Find(id);
            if (exams == null)
            {
                return HttpNotFound();
            }

            TempData["IDAnimal"] = exams.IDAnimal;
            
            return View(exams);
        }

        // POST: Exams/Edit/5
        // Per la protezione da attacchi di overposting, abilitare le proprietà a cui eseguire il binding. 
        // Per altri dettagli, vedere https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ExamID,ExamDate,Exam,ExamNotes")] Exams exams, int id)
        {
            if (ModelState.IsValid)
            {
                exams.ExamID= id;   
                exams.IDAnimal = Convert.ToInt32(TempData["IDAnimal"]);
                db.Entry(exams).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Details", "Animals", new { id = exams.IDAnimal});
            }
            
            return View(exams);
        }

Model 是一个简单的 DateTime 属性

编辑:这是模型:

 public partial class Exams
{
    [Key]
    public int ExamID { get; set; }

    public int IDAnimal { get; set; }

    [Column(TypeName = "date")]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime ExamDate { get; set; }

    [Required]
    [StringLength(30)]
    public string Exam { get; set; }

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

    public virtual Animals Animals { get; set; }
}

我真的不知道为什么它会这样,我唯一能想到的是日期格式存在一些问题,但我真的不知道如果不是以我在视图上使用的特定格式,我应该如何在页面上显示它

asp.net asp.net-mvc datetime datetimepicker datetime-format

评论

0赞 Md Farid Uddin Kiron 1/26/2023
你的模特长得怎么样,你能分享一下你的模特细节吗?
0赞 Luigicr95 1/26/2023
@MdFaridUddinKiron刚刚添加了代码
0赞 Panagiotis Kanavos 1/26/2023
0001-01-01是默认值,这意味着您正在尝试显示从未设置过的值。DateTime

答: 暂无答案