0

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" } })

1 Answer 1

1

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; }
   // ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you but the DataFormatString option of DisplayFormat attribute caused my problem. The input HTML element accepts only YYYY-MM-DD date format.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.