Reputation: 111
I created MVC application that has a text box posted to the database. When the text box is posted, I want to capture today's date from the view and store it into the table. How do I capture the date and time the view that posted and how do I pass this information into row Date within the database? Appreciate any help.
Controller
[HttpGet]
public ActionResult Pay(int accountNumber)
{
return View();
}
[HttpPost]
public ActionResult Pay(Payments payment )
{
if(ModelState.IsValid)
{
DB.Payment.Add(payment);
DB.SaveChanges();
var service = new Accounts(DB);
service.Updatepayee(payment.AccountNumber);
return RedirectToAction("Index", "Home");
}
return View();
}
Payments Class
public class Payments
public int Id { get; set; }
[Required]
[DataType(DataType.Currency)]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public decimal Amount { get; set; }
[Required]
public int AccountNumber {get; set;}
[RegularExpression(@"(^$)|(^\d{2}/\d{2}/\d{4})|(^((\d{1})|(\d{2}))/((\d{1})|(\d{2}))/(\d{4})\s((\d{1})|(\d{2}))[:]{1}((\d{1})|(\d{2}))[:]{1}((\d{1})|(\d{2}))\s((AM)|(PM)))", ErrorMessage = "Invalid Date")]
public DateTime TransactionDate { get; set; }
//Navigation property to check the account
public virtual AccountNumber accountNumber { get; set; }
}
Pay View
@model Credits.View.Payments
@{
ViewBag.Title = "Pay"; }
<h2>Payments</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Transaction</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Amount, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Amount, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Amount, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div> }
<div>
@Html.ActionLink("Back to List", "Index", "Home") </div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval") }
Upvotes: 0
Views: 270
Reputation: 41
[HttpPost]
public ActionResult Pay(Payments payment )
{
var d=DateTime.Now.ToUniversalTime();
if(ModelState.IsValid)
{
Payments p=new() Payments{
AccountNumber=p.AccountNumber,
Amount=payment.Amount,
TransactionDate=d
};
DB.Payment.Add(p);
DB.SaveChanges();
Upvotes: 0
Reputation: 55806
Couldn't you set it in the controller:
[HttpPost]
public ActionResult Pay(Payments payment )
{
if(ModelState.IsValid)
{
payment.TransactionDate = DateTime.Now.ToUniversalTime();
DB.Payment.Add(payment);
DB.SaveChanges();
Upvotes: 2