Search code examples
c#asp.net-corerazorasp.net-core-mvc

How to show DateTime.Now into Input Box


I am using ASP.NET Core 7.0 and tried to show DateTime.Now into Input box but did not show anything when the page was loaded.

See below all my codes.

Data Model:

public class DateShowVM
{
   [DataType(DataType.Date)]
   [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
   public DateTime TranDate { get; set; }
}

Action method:

public IActionResult Index()
{
    ViewBag.datenow = Convert.ToDateTime(DateTime.Now.ToString("dd/MM/yyyy"));    
    return View();
}

View:

<div class="form-group">
    <label asp-for="TranDate" class="control-label"></label>
    <input asp-for="TranDate" value="@ViewBag.datenow" readonly class="form-control" />
    <span asp-validation-for="TranDate" class="text-danger"></span>
</div>

Solution

  • If you want ONLY show (not editing) a date in specific format in the <input> tag it's easier to use type="text":

    <input asp-for="TranDate" class="form-control" type="text" 
             value="@ViewBag.datenow.ToString("dd/MM/yyyy")" readonly/>
    

    Take to account, that when you are using the ViewBag the data annotations like you declared in the DateShowVM class are become useless. It's necessary to specify the format in the ToString("dd/MM/yyyy") method.

    But when using the strongly typed view the data annotation is in the game. Therefore, it's enough to apply the required format to the property.

    Define data model and pass to the view:

    public IActionResult Index()
    {
        var model = new DateShowVM() { TranDate = DateTime.Now };
        return View(model);
    }
    

    The view code:

    @model DateShowVM
    
    <div class="form-group">
      <input asp-for="TranDate" class="form-control" type="text" readonly />
    </div>
    

    There are a lot of questions on the StackOverflow about using the input tag with type="date", but to support different date formats it's required to write the JavaScript code.