我将在哪里放置Date Time Now C#MVC

时间:2017-11-03 11:45:20

标签: c# asp.net-mvc datetime asp.net-core

我现在被困在哪里将DateTime Now属性放在我的MVC中。我有一个应用程序,有一个简单的表单来填写,目前,用户需要提交表单创建时的日期和时间区域,但我想在用户点击发送按钮时自动完成,在提交表单时在数据库中加上时间戳。我知道这需要使用DateTime Now来完成,但我有问题了解这个方法的位置。目前,我有一个DateTime {get;在我的模型文件夹中设置;}然后在我的cshtml页面中,这就是那里。我会在模型文件夹中用DateTime Now {get;}替换我的DateTime(get; set;}然后更新数据库,还是需要写出更多的逻辑,如果是这样的话,那么这个代码会被写入在与create方法关联的控制器中?

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; }


}

查看/汽车/索引     @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>

2 个答案:

答案 0 :(得分:0)

听起来你的控制器可能有一个Send()函数。

在发送功能的早期,你可以做到

model.CreationDate = DateTime.Now;

我会谨慎地将createdate设为只读并返回DateTime.Now,因为您将无法使用相同的模型来表示过去的模型。

答案 1 :(得分:0)

将DateTimeStamp字段添加到您的Cars模型中:

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; }


}

然后标记记录并保存:

[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);
}