Controller methods and views347 of 368 people found this helpful We have a good start to the movie app, but the presentation is not ideal. We don’t want to see the time on the release date and ReleaseDate should be two words. ![]() Open the Models/Movie.cs file and add the highlighted lines shown below: public class Movie{ public int ID { get; set; } public string Title { get; set; } [Display(Name = 'Release Date')] [DataType(DataType.Date)] public DateTime ReleaseDate { get; set; } public string Genre { get; set; } public decimal Price { get; set; }}
Visual studio adds Let’s remove the ![]() The updated code: using System;using System.ComponentModel.DataAnnotations;namespace MvcMovie.Models{ public class Movie { public int ID { get; set; } public string Title { get; set; } [Display(Name = 'Release Date')] [DataType(DataType.Date)] public DateTime ReleaseDate { get; set; } public string Genre { get; set; } public decimal Price { get; set; } }} We’ll cover DataAnnotations in the next tutorial. The Display attribute specifies what to display for the name of a field (in this case “Release Date” instead of “ReleaseDate”). The DataType attribute specifies the type of the data, in this case it’s a date, so the time information stored in the field is not displayed. Browse to the ![]() The Edit, Details, and Delete links are generated by the MVC Core Anchor Tag Helper in the Views/Movies/Index.cshtml file. td> a asp-action='Edit' asp-route-id='@item.ID'>Edita> | a asp-action='Details' asp-route-id='@item.ID'>Detailsa> | a asp-action='Delete' asp-route-id='@item.ID'>Deletea>td> Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files. In the code above, the AnchorTagHelper dynamically generates the HTML ![]() Recall the format for routing set in the Startup.cs file. app.UseMvc(routes =>{ routes.MapRoute( name: 'default', template: '{controller=Home}/{action=Index}/{id?}');}); ASP.NET Core translates Tag Helpers are one of the most popular new features in ASP.NET Core. See Additional resources for more information. Open the ![]() // GET: Movies/Edit/5public async TaskIActionResult> Edit(int? id){ if (id == null) { return NotFound(); } var movie = await _context.Movie.SingleOrDefaultAsync(m => m.ID == id); if (movie == null) { return NotFound(); } return View(movie);} // POST: Movies/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 TaskIActionResult> Edit(int id, [Bind('ID,Genre,Price,ReleaseDate,Title')] Movie movie){ if (id != movie.ID) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(movie); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!MovieExists(movie.ID)) { return NotFound(); } else { throw; } } return RedirectToAction('Index'); } return View(movie);} The Notice the second [HttpPost][ValidateAntiForgeryToken]public async TaskIActionResult> Edit(int id, [Bind('ID,Genre,Price,ReleaseDate,Title')] Movie movie){ if (id != movie.ID) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(movie); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!MovieExists(movie.ID)) { return NotFound(); } else { throw; } } return RedirectToAction('Index'); } return View(movie);} The [HttpPost] attribute specifies that this The [ValidateAntiForgeryToken] attribute is used to prevent forgery of a request and is paired up with an anti-forgery token generated in the edit view file (Views/Movies/Edit.cshtml). The edit view file generates the anti-forgery token in the Form Tag Helper. form asp-action='Edit'> The Form Tag Helper generates a hidden anti-forgery token that must match the The // GET: Movies/Edit/5public async TaskIActionResult> Edit(int? id){ if (id == null) { return NotFound(); } var movie = await _context.Movie.SingleOrDefaultAsync(m => m.ID == id); if (movie == null) { return NotFound(); } return View(movie);} When the scaffolding system created the Edit view, it examined the @model MvcMovie.Models.Movie@{ ViewData['Title'] = 'Edit';}h2>Edith2>form asp-action='Edit'> div class='form-horizontal'> h4>Movieh4> hr /> div asp-validation-summary='ModelOnly' class='text-danger'>div> input type='hidden' asp-for='ID' /> div class='form-group'> label asp-for='Genre' class='col-md-2 control-label'>label> div class='col-md-10'> input asp-for='Genre' class='form-control' /> span asp-validation-for='Genre' class='text-danger' /> div> div> div class='form-group'> label asp-for='Price' class='col-md-2 control-label'>label> div class='col-md-10'> input asp-for='Price' class='form-control' /> span asp-validation-for='Price' class='text-danger' /> div> div> div class='form-group'> label asp-for='ReleaseDate' class='col-md-2 control-label'>label> div class='col-md-10'> input asp-for='ReleaseDate' class='form-control' /> span asp-validation-for='ReleaseDate' class='text-danger' /> div> div> div class='form-group'> label asp-for='Title' class='col-md-2 control-label'>label> div class='col-md-10'> input asp-for='Title' class='form-control' /> span asp-validation-for='Title' class='text-danger' /> div> div> div class='form-group'> div class='col-md-offset-2 col-md-10'> input type='submit' value='Save' class='btn btn-default' /> div> div> div>form>div> a asp-action='Index'>Back to Lista>div>@section Scripts { @{await Html.RenderPartialAsync('_ValidationScriptsPartial');}} Notice how the view template has a The scaffolded code uses several Tag Helper methods to streamline the HTML markup. The - Label Tag Helper displays the name of the field (“Title”, “ReleaseDate”, “Genre”, or “Price”). The Input Tag Helper renders an HTML Run the application and navigate to the Processing the POST RequestThe following listing shows the [HttpPost][ValidateAntiForgeryToken]public async TaskIActionResult> Edit(int id, [Bind('ID,Genre,Price,ReleaseDate,Title')] Movie movie){ if (id != movie.ID) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(movie); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!MovieExists(movie.ID)) { return NotFound(); } else { throw; } } return RedirectToAction('Index'); } return View(movie);} The The model binding system takes the posted form values and creates a Before the form is posted to the server, client side validation checks any validation rules on the fields. If there are any validation errors, an error message is displayed and the form is not posted. If JavaScript is disabled, you won’t have client side validation but the server will detect the posted values that are not valid, and the form values will be redisplayed with error messages. Later in the tutorial we examine Model Validation validation in more detail. The Validation Tag Helper in the Views/Book/Edit.cshtml view template takes care of displaying appropriate error messages. ![]() All the |
|