Home > other >  how can get current datetime without submit in form
how can get current datetime without submit in form

Time:09-16

i have a submit form where has a input field for group name. I want to create a group name and stote in the database. when the group name create thats time i want to pick the current date and store in the model class propert. please give me suggestion. Advance thank you.

<input type="hidden" asp-for="DateTime.Date" class="form-control" />
<input asp-for="Name" type="text" class="form-control" id="inputName" 
placeholder="Group name">

 <script>
    $(function () {
        //Date picker
        $('#reservationdate').datetimepicker({
            format: 'L',
            format: 'dd/mm/yyyy'
        });
    }
</script>

model property public DateTime DateTime { get; set; } public string Name { get; set; }

CodePudding user response:

don't get the date from client side get it form the server side

use DateTime in c# to get the current date and store it

var date = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"); or use any date format you like

CodePudding user response:

Solution-1:

If you are using SQL server then directly use GETDATE() method in your insert and update queries.

Solution-2:

In your HTTP GET method when the page is loaded initialize the property as follow i.e.

    // Initialization.
    MyModel model = new MyModel();
    
    // Settings.
    model.DateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");

Then in your CSHTML file do following i.e.

<div class="form-group">
     @Html.HiddenFor(m => m.DateTime, new { @readonly = "readonly", placeholder = Html.DisplayNameFor(m => m.DateTime), @class = "form-control" })
</div>

The above HTML hidden field will preserve the datetime value, but, know that the time might not be accurate as it is not exact current, so, I recommend setting current date via database is right choice.

  • Related