Ryan
Ryan

Reputation: 31

Where would i place Date Time Now C# MVC

I am stuck right now on where to put the DateTime Now property in my MVC. I have an application that has a simple form to fill out, currently, the user is required to file out the date and time area of when the form was created, but I would like to have this automatically done when the user hits the send button, to put a time stamp in the database when the form was submitted. I am aware this needs to be done with the DateTime Now, but I am having issues understand where this method would be placed. Currently, i have a DateTime {get; set;} in my model's folder, then in my cshtml page this is there. Would I replace my DateTime (get; set;} with DateTime Now { get; } in the model's folder then update the database, or will there need to be some more logic written out, if so would this code be written in the controller associated with the create method?

Cars Controller
public class CarsController : Controller
{
    private readonly AutomobileContext _context;

    public CarsController(AutomobileContext context)
    {
        _context = context;
    }

    // GET: Cars
    public async Task<IActionResult> Index(string carsMake, string searchString)
    {

        var cars = from m in _context.Cars
                   select m;

        if (!String.IsNullOrEmpty(searchString))
        {
            cars = cars.Where(s => s.Make.Contains(searchString));
        }

        if (!String.IsNullOrEmpty(carsMake))
        {
            cars = cars.Where(x => x.Make == (carsMake));
        }

        var carsMakeVM = new CarsMakeViewModel();

        // use LINQ to get list of Make
        IQueryable<string> MakeQuery = from c in _context.Cars
                                       orderby c.Make
                                       select c.Make;
        carsMakeVM.Make = new SelectList(await MakeQuery.Distinct().ToListAsync());
        carsMakeVM.cars = await cars.ToListAsync();

        return View(carsMakeVM);
    }


    //return View(await _context.Cars.ToListAsync());

    // GET: Cars/Details/5
    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var cars = await _context.Cars
            .SingleOrDefaultAsync(m => m.Id == id);
        if (cars == null)
        {
            return NotFound();
        }

        return View(cars);
    }

    // GET: Cars/Create
    public IActionResult Create()
    {
        return View();
    }

    // POST: Cars/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Id,Make,Model,Color,licensePlate")] Cars cars)
    {
        if (ModelState.IsValid)
        {
            _context.Add(cars);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(cars);
    }

    // GET: Cars/Edit/5
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var cars = await _context.Cars.SingleOrDefaultAsync(m => m.Id == id);
        if (cars == null)
        {
            return NotFound();
        }
        return View(cars);
    }

    // POST: Cars/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, [Bind("Id,Make,Model,Color,licensePlate")] Cars cars)
    {
        if (id != cars.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(cars);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CarsExists(cars.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
        return View(cars);
    }

    // GET: Cars/Delete/5
    public async Task<IActionResult> Delete(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var cars = await _context.Cars
            .SingleOrDefaultAsync(m => m.Id == id);
        if (cars == null)
        {
            return NotFound();
        }

        return View(cars);
    }

    // POST: Cars/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(int id)
    {
        var cars = await _context.Cars.SingleOrDefaultAsync(m => m.Id == id);
        _context.Cars.Remove(cars);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    private bool CarsExists(int id)
    {
        return _context.Cars.Any(e => e.Id == id);
    }
}

}

Models Folder/Cars
public class Cars
{
    public int Id { get; set; }


    //[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
    [StringLength(60, MinimumLength = 3)]
    [Required]
    public string Make { get; set; }


    //[StringLength(60, MinimumLength = 3)]
    [Required]
    public string Model { get; set; }

    //[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
    [StringLength(60, MinimumLength = 3)]
    [Required]
    public string Color { get; set; }

    [Display(Name=" License Plate")]
    [StringLength(60, MinimumLength = 3)]
    [Required]
    public string licensePlate { get; set; }


}

Views/Cars/Index @model SPVT.Models.CarsMakeViewModel;

@{
    ViewData["Title"] = "Vehicles";
}

<h2></h2>

<p>
    <a asp-action="Create">Create New Vehicle </a>
</p>

<form asp-controller="Cars" asp-action="Index" method="get">
<p>
    <select asp-for="carsMake" asp-items="Model.Make">
        <option value="">All</option>
    </select>


search: <input type="text" name="searchString" placeholder="Search Make">
<input type="submit" value="Filter" />

</p>

</form>

<table class="table">
    <thead>
        <tr>
                <th>
                    @Html.DisplayNameFor(model => model.cars[0].Make)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.cars[0].Model)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.cars[0].Color)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.cars[0].licensePlate)
                </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model.cars) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Make)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Model)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Color)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.licensePlate)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>

Upvotes: 0

Views: 1705

Answers (2)

jon.r
jon.r

Reputation: 1058

Add DateTimeStamp field to your Cars model:

public class Cars
{
    public int Id { get; set; }

    public DateTime DateTimeStamp {get; set;}

    //[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
    [StringLength(60, MinimumLength = 3)]
    [Required]
    public string Make { get; set; }


    //[StringLength(60, MinimumLength = 3)]
    [Required]
    public string Model { get; set; }

    //[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
    [StringLength(60, MinimumLength = 3)]
    [Required]
    public string Color { get; set; }

    [Display(Name=" License Plate")]
    [StringLength(60, MinimumLength = 3)]
    [Required]
    public string licensePlate { get; set; }


}

Then stamp the record and save it:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Make,Model,Color,licensePlate")] Cars cars)
{
    if (ModelState.IsValid)
    { 
        cars.DateTimeStamp = DateTime.Now;
        _context.Add(cars);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    return View(cars);
}

Upvotes: 1

Ryan Donahue
Ryan Donahue

Reputation: 48

It sounds like you might have have a Send() function in your controller.

So early in the send function you could do

model.CreationDate = DateTime.Now;

I would be wary of making the creationdate read only and returning DateTime.Now as you will not be able to use that same model to represent models from the past.

Upvotes: 0

Related Questions