我正在使用 ViewModel 在我的数据库中创建一个新项目,ViewModel 只有我希望用户能够设置的属性,当它被回发时,我创建一个新的“真实”对象并将其保存到D B。
我正在这样做,如下所述
[HttpGet]
public ActionResult Create(int id = 0)
{
var opt = unitOfWork.OptionRepository.GetByID(id);
CreateAvailabilityViewModel model = new CreateAvailabilityViewModel();
model.OptionDescription = opt.Description;
model.CentreCode = opt.CentreCode;
model.OptionID = id;
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CreateAvailabilityViewModel cavm)
{
if (ModelState.IsValid)
{
OptionAvailability newOA = new OptionAvailability();
DateTime now = DateTime.Now;
newOA.ChangedDate = newOA.CreatedDate = now;
newOA.ChangedBy = newOA.CreatedBy = User.Identity.Name;
newOA.DateFrom = cavm.DateFrom;
newOA.DateTo = cavm.DateTo;
newOA.MinNumbers = cavm.MinNumbers;
newOA.MaxNumbers = cavm.MaxNumbers;
newOA.OptionID = cavm.OptionID;
unitOfWork.OptionAvailabilityRepository.Insert(newOA);
unitOfWork.Save();
return RedirectToAction("Detail", "Option", new { id = newOA.OptionID });
}
return View(cavm);
}
这是 ViewModel
public class CreateAvailabilityViewModel
{
[HiddenInput(DisplayValue = false)]
public int OptionAvailabilityID { get; set; }
[HiddenInput(DisplayValue = false)]
public int OptionID { get; set; }
[Required]
public DateTime DateFrom { get; set; }
[Required]
public DateTime DateTo { get; set; }
[Required]
public int MinNumbers { get; set; }
[Required]
public int MaxNumbers { get; set; }
public string CentreCode { get; set; }
public string OptionDescription { get; set; }
}
我面临的问题是,当呈现表单时,日期和整数的表单字段默认为 01/01/0001 和 0 而不是空白。我正在使用 Html.EditorFor 助手来呈现输入我认为这是因为在 HttpGet Create 方法中,当我实例化 ViewModel 时,它使用类型默认值,然后在对象中将它们传递给表单,但这不是 wha t我想发生..我需要将这些属性设置为DateTime?
和/或int?
吗?
我很确定这是使用的好习惯,但是对于为什么有人可以解释我做错了什么有点困惑,非常感谢