简体   繁体   English

ASP.NET MVC EditorFor和DateTime默认值

[英]ASP.NET MVC EditorFor and DateTime default value

I want to set default value for an EditorFor HTML helper but just the helper text is displayed in it. 我想为EditorFor HTML帮助程序设置默认值,但其中仅显示帮助程序文本。 Why EditorFor does not let me to set its default value, please? 为什么EditorFor不允许我设置其默认值?

class Person {
   public int Id  { get; set; }
   public DateTime DateOfBirth { get; set; }
   ...
}

class PersonVM {
   public Person { get; set; }
   ...
}

public ActionResult Edit(int id)
{
   var vm = new PersonVM ();
   vm.Person = db.Persons.Where(x => x.Id == id).FirstOrDefault();
   ...
   return View(vm);
}

@model Project.Models.PersonVM 
@Html.EditorFor(model => model.Person.DateOfBirth , new { htmlAttributes = new { @class = "form-control" } })

Set the default value by assigning a value to the model property. 通过为模型属性分配值来设置默认值。

Either in the Controller Action: 在控制器动作中:

public ActionResult Edit(int id) {
   var vm = new PersonVM ();
   vm.Person = db.Persons.Where(x => x.Id == id).FirstOrDefault();
   if (vm.Person.DateOfBirth == default(DateTime)) {
       vm.Person.DateOfBirth = new DateTime(1900, 01, 01); // default value
   }
   // ...
   return View(vm);
}

Or in the ViewModel (make sure that you only map valid DateOfBirth from the DB to the ViewModel): 或在ViewModel中(确保仅将有效的DateOfBirth从数据库映射到ViewModel):

public class PersonVM {
   public PersonViewModel () {
       DateOfBirth = new DateTime(1900, 01, 01); // default value
   }

   public int Id  { get; set; }
   public DateTime DateOfBirth { get; set; }
   // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM