Show current date in Editorfor Razor

Asked

Viewed 1,798 times

2

People would like to know how to insert the current date into a @Html.Editorfor? I’ve searched a lot of places but so far I’ve got nothing.

  • Without any additional details it usually does not help, see this: http://stackoverflow.com/questions/7124434/display-only-date-and-no-time

2 answers

3


@Html.EditorFor is a component that binds to an item in your Model (or Viewmodel, if applicable). Therefore, if your class has such a field:

public DateTime MeuCampoData { get; set; }

You just have to set the field MeuCampoData with the current date on Controller.

meuModel.MeuCampoData = DateTime.Now;

Attention to create records actions (such as the case of Create). In doing this:

return View();

You’re passing a Model emptiness to the View. For these cases, it is necessary to define a Model new in Controller, set the date and then pass this Model to the View:

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

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

@Html.EditorFor(model => model.MeuCampoData);

0

@Html.Label(@DateTime.Now.ToShortDateString(), new { @class = "css-class" })

Browser other questions tagged

You are not signed in. Login or sign up in order to post.