Reputation: 41
I want to display today's date in my film creation form.
Controller:
// GET: Movies/Create
public IActionResult Create()
{
ViewData["IdGenre"] = new SelectList(_context.Genres, "IdGenre", "Name");
return View();
}
// POST: Movies/Create
// To protect from overposting attacks, 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,Name,DateDeSortie,Stock,IdGenre")] Movie movie)
{
if (ModelState.IsValid)
{
_context.Add(movie);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["IdGenre"] = new SelectList(_context.Genres, "IdGenre", "Name", movie.IdGenre);
return View(movie);
}
Model:
[DataType(DataType.Date)]
[Display(Name = "Date de sortie")]
[Required(AllowEmptyStrings =false,ErrorMessage ="La date est requise")]
public DateTime? DateDeSortie { get; set; }
View:
<div class="form-group">
<label asp-for="DateDeSortie" class="control-label"></label>
<input asp-for="DateDeSortie" class="form-control" />
<span asp-validation-for="DateDeSortie" class="text-danger"></span>
</div>
Thank you for your help I have been stuck for several days
Upvotes: 3
Views: 2187
Reputation: 28057
In my opinon, you could directly set the create view's input tag's value to today's value. To acheve this things, we could do it by using js or directly using @DateTime.Now.ToString("yyyy-MM-dd")
More details, you could refer to below codes:
<div class="form-group">
<label asp-for="DateDeSortie" class="control-label"></label>
<input asp-for="DateDeSortie" class="form-control" value="@DateTime.Now.ToString("yyyy-MM-dd")" />
<span asp-validation-for="DateDeSortie" class="text-danger"></span>
</div>
Result:
Upvotes: 2
Reputation: 104
Add this code to your View. This will get today's date. This may or may not be what you're looking for.
@Html.Label("DateCreated", DateTime.Today.ToShortDateString().ToString(), new { @readonly = "readonly" })
Upvotes: 2