C# 在C语言中面临验证问题#
我想向用于更改事件日期的表单添加验证。如果用户忘记选择新日期,我想通知他们应该选择一个新日期 在我的模型中,我对该特定属性使用了数据注释,如下所示:C# 在C语言中面临验证问题#,c#,asp.net-mvc,validation,C#,Asp.net Mvc,Validation,我想向用于更改事件日期的表单添加验证。如果用户忘记选择新日期,我想通知他们应该选择一个新日期 在我的模型中,我对该特定属性使用了数据注释,如下所示: [Required] public DateTime Estimated_Start_Date { get; set; } 这是更改日期的控制器 public ActionResult Change(int? Id) { var dtl = _context.pm_main_repz.Include(a =
[Required]
public DateTime Estimated_Start_Date { get; set; }
这是更改日期的控制器
public ActionResult Change(int? Id)
{
var dtl = _context.pm_main_repz.Include(a => a.PM_Evt_Cat).SingleOrDefault(a => a.Id == Id);
if (dtl == null)
{
return Content("No item found!");
}
var vm = new PM_InsertEdit_ViewModel()
{
pm_main_rep = dtl,
};
return View(vm);
}
这是更改日期的视图
@model Project.ViewModel.PM_InsertEdit_ViewModel
@using (Html.BeginForm("ChangeDate", "PM", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<label>Select New Date</label>
@Html.TextBoxFor(a => a.pm_main_rep.Estimated_Start_Date, new { @class = "form-control"})
@Html.ValidationMessageFor(a=> a.pm_main_rep.Estimated_Start_Date)
</div>
@Html.AntiForgeryToken();
@Html.HiddenFor(a => a.pm_main_rep.Id);
<button class="btn btn-primary">Request</button>
}
请注意,到目前为止,如果我不通过检查ModelState来强制验证,那么一切都正常,但是如果我这样做,它将无法识别代码的一部分,并用红色下划线
这是我想在ChangeDate方法中检查ModelState时的代码。基本上,我希望用户应该保持在相同的视图中,除非他们选择一个新的日期
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ChangeDate(PM_InsertEdit_ViewModel ap)
{
if (!ModelState.IsValid)
{
var dtl = _context.pm_main_repz.Include(a => a.PM_Evt_Cat).SingleOrDefault(a => a.Id == Id); // Note: It underlines the Id with red and says: The Name Id does not exist in the current context
var vm = new PM_InsertEdit_ViewModel()
{
pm_main_rep = dtl,
};
return View("Change",vm);
}
var item = _context.pm_main_repz.Single(a => a.Id == ap.pm_main_rep.Id);
item.Estimated_Start_Date = ap.pm_main_rep.Estimated_Start_Date;
_context.SaveChanges();
return RedirectToAction("Success", "PM");
}
错误如下:
[Required]
public DateTime Estimated_Start_Date { get; set; }
当前上下文中不存在名称Id
虽然我很快就能解决这个问题,但我在逻辑上有些困惑 ModelState.IsValid仅使用默认的模型绑定器进行验证,该绑定器在代码中是PM\u InsertEdit\u ViewModel。这不是您得到的编译器错误的一部分。您可以尝试删除该行,然后将ap参数返回到视图,如下所示:returnview(“Change”,ap)
当IsValid为not valid时,您将返回操作收到的数据,以便用户可以编辑其输入 在这一行:
SingleOrDefault(a=>a.Id==Id)
,第二个Id应该是什么?@TanvirArjel这一行,var dtl=\u context.pm\u main\u repz.Include(a=>a.pm\u Evt\u Cat).SingleOrDefault(a=>a.Id==Id)@TanvirArjel写一个答案,这对OP也有帮助,对未来的读者也有帮助。像这样的质量保证网站的精神是回答问题。我很高兴@johnkamalhello,这是一个类似的问题,有时间的时候请看一下。。提前谢谢