MVC II §Slavomír Moroz §2015 Topics •ViewData •Routing •Razor blocks syntax •Model binding •Model validation •Templates •AntiForgeryToken §MVC 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 ViewData.Model = X vs. return View(X) ViewData[“”] vs Viewbag Breakpoint in DetailsView - ModelMetadata RouteData §MVC Route constraints §MVC Number vs string constraint Add GuidRouteConstraint Attribute routing §MVC Razor syntax - blocks §MVC Model binding - passing data §MVC Simple binding Create(GameGenreEnum genre, string name, DateTime publishedOn) Complex binding Create(product product) PartialEdit(ID) + UpdateModel Post – redirect – get UpdateModel(product, “”) TryUpdateModel(product, “”) MapperUpdate Security issue when domain model = view model. Post data: book.owner.roles[0] = “administrator” Collections: simple array, array of complex types, dictionary (demo checkbox list) BindAttribute, FromBody, FromUri Partial binding §MVC Collections binding §MVC Primitive array not working in demo cos of checkbox false value which is adding extra value to non indexed array. Model validation (server) §MVC BadRequest in WebApi Model state data persists Model validation (client) •Unobtrusive validation (linked with JQuery) •Supports only attribute validators (doesn’t support IValidatableObject) •Hard to localize (JQuery globalize project) • §Setup •Install nugget package Microsoft.JQuery.Unobtrusive.Validation •Link scripts in your layout: •JQuery •JQuery-validate •JQuery-validate-unobtrusive § § §http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html §http://jqueryvalidation.org/documentation/ §https://github.com/jquery/globalize § § §MVC Templates •You can create custom templates for displaying or editing objects •Templates must be placed in folder •DisplayTemplates •EditorTemplates § •Rendered with command •Html.DisplayFor() •Html.EditorFor() • •How is template selected 1.Explicit 2.[DataType] attribute 3.By type 4. §(Example: see FilterIndexedArrayWithTemplate.cshtml & views under Shared folder in demo app) §MVC AntiForgeryToken •Protection against CSRF attacks. •Render token in form •Html.AntiForgeryToken() •Validation in controller •[ValidateAntiForgeryToken] attribute • • • • • • §https://en.wikipedia.org/wiki/Cross-site_request_forgery § §MVC