0
votes

I'm new to razor and .net, i have a page on an ASP Net Razor project where i popup a modal with a form inside. Inside the form there is a datepicker and i want to set the system date when the page loads and evenly keep it editable. i've already tried with

  • @{ string dateNow = DateTime.Now.ToString("dd MM yyyy"); }
  • <input asp-for="intervento.Data" class="form-control" type="date" value="@dateNow" />

it retrieves the correct date but can't display it. how can i solve this?

3

3 Answers

1
votes

Your date should be in the following format yyyy-MM-dd.

So it would look like this:

<input type="date" value="2020-10-23">
0
votes

Presumably, Intervento.Data is a DateTime property of your PageModel? If so, you should add a DataType attribute to specify that it represents a date, not a time:

[DataType(DataType.Date)]
public DateTime Data { get; set; }

Then you don't need to specify the type on the input. The tag helper will generate the correct value based on the attribute. Also, if you set a default value on the property:

[DataType(DataType.Date)]
public DateTime Data { get; set; } = DateTime.Now;

you won't need to set the value of the input either. ASP.NET will take care of formatting the value correctly to an ISO 8601 format that the input can work with. So the following will suffice:

<input asp-for="intervento.Data" class="form-control" />
-1
votes

In my opinion, a better approach to this is:

Instead of doing this

@{ string dateNow = DateTime.Now.ToString("dd MM yyyy"); }

Set the value of datetime using the constructor and remove

value="@dateNow"

Razor page will automatically return the property value which we set in the constructor.

So the constructor of the razer page becomes:

    public DateTime Date { get; set; }
    public IndexModel(ILogger<IndexModel> logger)
    {
        _logger = logger;
        Date = DateTime.Now;
    }