简体   繁体   中英

How can a text box automatically pic the date and time before submitting a form in asp.net c# MVC?

I am working on a razor view, that submits a form to database. It has three textboxes to store the title, amount and Date.

Although it works properly, But I don't want to enter the date manually, I want the form to automatically pick the date and time while submitting a form in a hidden manner, not allowing the users to change the date and time while submitting the form.

This is the razor view:

@using (Html.BeginForm("Request", "Requester", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
    @Html.LabelFor(a => a.title)
    @Html.TextBoxFor(a => a.title, new { @class = "form-control" })
</div>
<div class="form-group">
    @Html.LabelFor(a => a.amount)
    @Html.TextBoxFor(a => a.amount, new { @class = "form-control" })
</div>

<div class="form-group">
    @Html.LabelFor(a => a.date_and_time)
    @Html.TextBoxFor(a => a.date_and_time, new { @class = "form-control" })
</div>
<button class="btn btn-primary">Request</button>
}

This is the model:

   public class Events
{
    public int Id { get; set; }
    public string title { get; set; }
    public string amount { get; set; }
    public DateTime date_and_time { get; set; }

  }

You can do something like this

        [HttpPost]
    public ActionResult Request(Events event)
    {
        event.date_and_time = DateTime.Now();

        //then do other operations or just save it in the the database
    }

There are two simple approaches.

Approach 1

<div class="form-group">
    @Html.LabelFor(a => a.date_and_time)       
    <input type="datetime-local"...>
</div>

Approach 2

<div class="form-group">
    @Html.TextBoxFor(a => a.date_and_time, new { @type = "date", @class = "form-control 
datepicker" })
</div>

Approach 2, unfortunately, only supports type "date". You may also consider using jquery datetimepicker or Bootstrap datetimepicker.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM