Show current date in EditorForRazor

2

People would like to know how to insert the current date into an @Html.EditorFor? I've looked in several places but so far I have not achieved anything.

    
asked by anonymous 15.10.2015 / 04:56

2 answers

3

@Html.EditorFor is a component that attaches to some item in your Model (or ViewModel as well). So if your class has a field like this:

public DateTime MeuCampoData { get; set; }

You should only set the MeuCampoData field to the current date in the Controller .

meuModel.MeuCampoData = DateTime.Now;

Attention to record creation actions (such as Create ). When doing this:

return View();

You are passing an Model empty to View . For these cases, you need to define a new Model in Controller , set the date and then pass this Model in>:

var meuModel = new MeuModel {
    meuModel.MeuCampoData = DateTime.Now;
};
return View(meuModel);

Done this correctly, @Html.EditorFor() will correctly display the current date:

@Html.EditorFor(model => model.MeuCampoData);
    
15.10.2015 / 05:14
0
@Html.Label(@DateTime.Now.ToShortDateString(), new { @class = "css-class" })
    
11.07.2017 / 16:12