MVC 6 introduction §Slavomír Moroz §2016 MVC Pattern •Model-View-Controller architectural pattern for user-interface design (1970 – 1980) •Ruby on Rails, ASP.NET MVC, Spring MVC, … • §Model – state of an aspect of the application §View – displays user interface using provided model §Controller – handles user interaction by amending model and passing it to a view § § § §https://docs.asp.net/en/latest/mvc/overview.html § § §MVC 6 introduction File:MVC-Process.svg Create MVC application from template -Show structure, startup, bower, staticfiles Routing •Convention-based routing • §routes.MapRoute(name: "Default", template: "{controller=Home}/{action=Index}/{id?}"); § •Attribute routing • §[Route("api/[controller]")] §public class ProductsController : Controller §{ § [HttpGet("{id}")] § public IActionResult GetProduct(int id) § { § ... § } §} § §https://docs.asp.net/en/latest/mvc/controllers/routing.html § § §MVC 6 introduction Browse default UI showing controllers in action Create an route without controller (for HomeController) Mixed routing – RouteAttribute overrides conventional IActionConstraint – HttpPost, ActionName… Controllers •In ASP.NET MVC, a Controller is used to define and group a set of actions. An action (or action method) is a method on a controller that handles incoming requests. § •New controller instance for each request • •Actions should return an instance of IActionResult (or Task for async methods) that produces a response. • •https://docs.asp.net/en/latest/mvc/controllers/actions.html#defining-actions • §MVC 6 introduction Structure, activator, Go to link, show ActionResult helper methods Views •ASP.NET Core MVC views are .cshtml files stored by default in a Views folder within the application. § •When an action returns a view, a process called view discovery takes place. •Unless a specific view file is specified, the runtime looks for a controller-specific view first, then looks for matching view name in the Shared folder. 1.Views//.cshtml 2.Views/Shared/.cshtml • •When an action returns the View method, like so return View();, the action name is used as the view name •A view name can be explicitly passed to the method (return View("SomeView");). § § §https://docs.asp.net/en/latest/mvc/views/overview.html § §MVC 6 introduction Edit index, remove the markup, put some label in it. Show bootstrap doc for classes. Razor §MVC 6 introduction https://docs.asp.net/en/latest/mvc/views/razor.html Implicit expression @datime Explicit

Last week this time: @(DateTime.Now - TimeSpan.FromDays(7))

ViewData (ViewDataDictionary Class) •Represents a container that is used to pass data between a controller and a view •Controllers writes the data, view reads. • •ViewData.Model – passed model •ViewData.ModelMetadata – set o information about model •ViewData.ModelState – validation messages •ViewData[“something”] – additional data •also accessible via ViewBag. • § § §https://msdn.microsoft.com/en-us/library/system.web.mvc.viewdatadictionary(v=vs.118).aspx § • §MVC 6 introduction ViewData.Model = X vs. return View(X) ViewData[“”] vs Viewbag Show example of both Layouts §MVC 6 introduction Show title Layouts •Specifying a Layout §@{ § Layout = "_Layout"; §} § •Layout must call RenderBody. Wherever the call to RenderBody is placed, the contents of the view will be rendered. • •Running Code Before Each View §If you have code you need to run before every view, this should be placed in the _ViewStart.cshtml file. § §https://docs.asp.net/en/latest/mvc/views/layout.html • §MVC 6 introduction Sections •RenderSection(…) in layout (usually) •Used for view-specific HTML that is not part of body (RenderBody()) •Side bars, adds, action-specific content •Scripts (~/Views/Shared/_Layout.cshtml) •Not required to be defined in all views (usually, required: false) § §MVC 6 introduction Show scripts section Add to home: @section scripts { } View model •Models folder •Represent state of a particuallar aspect of the application •Each controller should have a sub-folder for its models •Models are usually named by corresponding Actions •Always prefer strongly-typed model to a ViewBag or ViewData •Models should be POCO objects without any business logic § § § § § §https://en.wikipedia.org/wiki/Plain_Old_CLR_Object § • §MVC 6 introduction Show scaffolding Switch to project before from zip folder Show Index action – view, model, controller, automapper mapping View helpers §@model MyProject.Models.Product § §@using (Html.BeginForm()) §{ §
§ @Html.LabelFor(m => p.Name, "Name:") § @Html.TextBoxFor(m => p.Name) §
§ §} §MVC 6 introduction §@model MyProject.Models.Product §@addtaghelper "Microsoft.AspNet.Mvc.TagHelpers" § §
§
§ § §
§ § §
https://docs.asp.net/en/latest/mvc/views/tag-helpers/index.html https://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper_methods(v=vs.118).aspx Add link to layout to games index Details vs create views Model display attributes Import file with inject and usings Route constraints •Route constraints generally inspect the route value associated via the route template and make a simple yes/no decision about whether or not the value is acceptable. • •Avoid using constraints for input validation, because doing so means that invalid input will result in a 404 (Not Found) instead of a 400 with an appropriate error message. • •template: “edit/{id:int}“ •defaults: new { controller=“IdObjectController", action=“Edit" } § •template: “edit/{guid:guid}“ •defaults: new { controller=“GuidObjectController", action=“Edit" } • •https://docs.asp.net/en/latest/fundamentals/routing.html#route-constraint-reference • §MVC 6 introduction Add id rule to routes, create game with integer codename Model validation (server) §MVC 6 introduction Add attributes and IValidatableObject to view mode create Show validation place holders in view Show modelState check Post – redirect – get Model validation (client) •Unobtrusive validation (linked with JQuery) •Supports only attribute validators (doesn’t support IValidatableObject) •Custom attributes that implements IClientModelValidator •Hard to localize §Setup •Install nugget package Microsoft.JQuery.Unobtrusive.Validation •Link scripts in your layout: •JQuery •JQuery-validate •JQuery-validate-unobtrusive § §MVC 6 introduction Do nothing Partial views •Html.Partial(…) – displays view of given name (no controller/action is called) •Html.RenderAction(…) – calls a controller‘s action, rendering its result •always use PartialViewResult •Usually view name starts with an underscore § § § § § § § § §https://docs.asp.net/en/latest/mvc/views/partial.html § §MVC 6 introduction Place _ValidationScriptsPartial to script section in create view Explain void methods in views – in link there is a difference between Partial() and RenderPartial Model binding - passing data §MVC 6 introduction Customize binding behavior •MVC contains several attributes that you can use to direct its default model binding behavior to a different source. •[BindRequired]: This attribute adds a model state error if binding cannot occur. •[BindNever]: Tells the model binder to never bind to this parameter. •[FromHeader], [FromQuery], [FromRoute], [FromForm]: Use these to specify the exact binding source you want to apply. •[FromServices]: This attribute uses dependency injection to bind parameters from services. •[FromBody]: Use the configured formatters to bind data from the request body. The formatter is selected based on content type of the request. •[ModelBinder]: Used to override the default model binder, binding source and name. • • §https://docs.asp.net/en/latest/mvc/models/model-binding.html § §MVC 6 introduction Add bind attribute, list all desired properties, security Collections binding §MVC 6 introduction Primitive array not working in demo from lecture 5 2015 cos of checkbox false value which is adding extra value to non indexed array. AntiForgeryToken •Protection against CSRF attacks. § •Render token in form •generates the anti-forgery token with the Form Tag Helper •
• •Validation in controller •[ValidateAntiForgeryToken] attribute • • • • • • §https://en.wikipedia.org/wiki/Cross-site_request_forgery § §MVC 6 introduction Context •HttpContext (IHttpContextAccessor service dependency injection) •Request •Response •Session data •Authentized user § •ActionContext (IActionContextAccessor service dependency injection) •Action metadata •ModelState •RouteData •Encapsulates information about a route. •Route parameters and values • §MVC 6 introduction Resources §https://docs.asp.net/en/latest/mvc/overview.html •Complete documentation •MVC part is well written •Still in progress, some parts are missing § §https://docs.asp.net/en/latest/tutorials/first-mvc-app/controller-methods-views.html •Quick start tutorial § §MVC 6 introduction Mention config override from environment variable, useful for source control