简体   繁体   中英

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. Why EditorFor does not let me to set its default value, please?

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):

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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