Łukasz Trzewik
Łukasz Trzewik

Reputation: 1165

Default value for Create form in mvc

I would like to set a default value of a text area in my asp.net mvc 5 application. I have a field in my Patient model that looks like this:

    [Display(Name = "Date of Birth")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    [Required]
    public DateTime DateOfBirth { get; set; }

and i would like to set the default value of this field to the current date. Right now it is displaying this form : http://scr.hu/11m6/lf9d5 . I have already tried using the constructor and setting the value of DateOfBirth in it :

    public Patient()
    {
        DateOfBirth = DateTime.Now;
    }

but it had no effect. I also tried editing my view .cshtml file to this:

@Html.EditorFor(model => model.DateOfBirth, new { @value = "2014-05-05" })

but it also had no effect. Does anyone know a solution to this ?

Upvotes: 3

Views: 8249

Answers (1)

Łukasz W.
Łukasz W.

Reputation: 9755

You should create an instance of Patient class and pass it to the view in your Create action. In your case view model is not set, so it does not enters Patient class constructor and does not use DateTime.Now value to be displayed.

Try changing your Create action method from:

    // GET: /Patient/Create
    public ActionResult Create()
    {
        return View();
    }

to:

    // GET: /Patient/Create
    public ActionResult Create()
    {
        var patient = new Patient();
        return View(patient);
    }

Upvotes: 13

Related Questions