mvc中创建表单的默认值

Łuk*_*wik 3 c# model-view-controller asp.net-mvc

我想在我的asp.net mvc 5应用程序中设置文本区域的默认值.我的Patient模型中有一个字段如下所示:

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

我想将此字段的默认值设置为当前日期.现在它显示这个表格:http://scr.hu/11m6/lf9d5.我已经尝试使用构造函数并在其中设置DateOfBirth的值:

    public Patient()
    {
        DateOfBirth = DateTime.Now;
    }
Run Code Online (Sandbox Code Playgroud)

但它没有效果.我也尝试编辑我的视图.cshtml文件到这个:

@Html.EditorFor(model => model.DateOfBirth, new { @value = "2014-05-05" })
Run Code Online (Sandbox Code Playgroud)

但它也没有效果.有谁知道解决这个问题?

Łuk*_*.pl 11

您应该创建一个Patient类实例并将其传递给操作中的视图Create.在您的情况下,视图模型未设置,因此它不会进入Patient类构造函数,也不会使用DateTime.Now值来显示.

尝试更改您的Create操作方法:

    // GET: /Patient/Create
    public ActionResult Create()
    {
        return View();
    }
Run Code Online (Sandbox Code Playgroud)

至:

    // GET: /Patient/Create
    public ActionResult Create()
    {
        var patient = new Patient();
        return View(patient);
    }
Run Code Online (Sandbox Code Playgroud)

  • 一年后,它仍然有效. (2认同)