Working with Data Model Binders, Display Templates, Editor Templates, Validation… SoftUni Team Technical Trainers Software University

Slides:



Advertisements
Similar presentations
Telerik School Academy ASP.NET MVC.
Advertisements

AngularJS Routing Routes, Route Parameters, Templates, Location, Navigation SoftUni Team Technical Trainers Software University
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
Software University Curriculum, Courses, Exams, Jobs SoftUni Team Technical Trainers Software University
PHP Basics Course Introduction SoftUni Team Technical Trainers Software University
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Nikolay Kostov Telerik Software Academy Senior Software Developer and Trainer
Project Tracking Tools Trello, Asana, Basecamp, GitHub Issue Tracker, TRAC SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
Design Patterns: Structural Design Patterns
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
JavaScript Design Patterns Private Fields, Module, Revealing Module, Revealing Prototype, … Software University Technical Trainers SoftUni.
NoSQL Databases NoSQL Concepts SoftUni Team Technical Trainers Software University
Consuming REST Services from C# SoftUni Team Technical Trainers Software University
Entity Framework Performance SoftUni Team Technical Trainers Software University
Microsoft Azure SoftUni Team Technical Trainers Software University
Svetlin Nakov Technical Trainer Software University
Build Processes and Continuous Integration Automating Build Processes Software University Technical Trainers SoftUni Team.
Processing Redis with.NET How to Operate with Redis Databases SoftUni Team Technical Trainers Software University
Project Tracking Tools Trello, Asana, Basecamp, GitHub Issue Tracker, TRAC Angel Georgiev Part-time Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
Templating, Routing, lodash Extending functionality using Collections SoftUni Team Technical Trainers Software University
ASP.NET MVC Architecture Layouts, Filters, Sections, Helpers, Partial Views, Areas… SoftUni Team Technical Trainers Software University
AMD and RequireJS Splitting JavaScript Code into Dependent Modules Software University Technical Trainers SoftUni Team.
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
Sessions and Cookies State Management, Cookies, Sessions, Hidden Fields SoftUni Team Technical Trainers Software University
Controls, Widgets, Grid…
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
ASP.NET SignalR SoftUni Team Technical Trainers Software University
Responsive Design Design that Adapts to Different Devices SoftUni Team Technical Trainers Software University
Processing JSON in.NET JSON, JSON.NET LINQ-to-JSON and JSON to XML SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability Svetlin Nakov Technical Trainer Software University
High-Quality Code: Course Introduction Course Introduction SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns General and reusable solutions to common problems in software design Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
ASP.NET Identity System
Virtual techdays INDIA │ 9-11 February 2011 SESSION TITLE Kamala Rajan S │ Technical Manager, Marlabs.
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
JavaScript Tools Tools for Writing / Editing / Debugging JavaScript Code Svetlin Nakov Technical Trainer Software University
ORM Basics Repository Pattern, Models, Entity Manager Ivan Yonkov Technical Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding Svetlin Nakov Technical Trainer Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
JavaScript Applications Course Introduction SoftUni Team Technical Trainers Software University
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Programming Fundamentals Course Introduction SoftUni Team Technical Trainers Software University
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
Team Work and Personal Skills Course Introduction Angel Georgiev Part-time Trainer Software University
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
Web Storage and Cookies Cookies, Local and Session Storage SoftUni Team Technical Trainers Software University
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
Auto Mapping Objects SoftUni Team Database Applications
ASP.NET Essentials SoftUni Team ASP.NET MVC Introduction
Introduction to MVC SoftUni Team Introduction to MVC
Introduction to Entity Framework
Mocking tools for easier unit testing
Entity Framework: Code First
ASP.NET Razor Engine SoftUni Team ASP.NET MVC Introduction
MVC Architecture, Symfony Framework for PHP Web Apps
ASP.NET MVC Introduction
Best Practices and Architecture
Best practices and architecture
Extending functionality using Collections
Manual Mapping and AutoMapper Library
ASP.NET Razor Engine SoftUni Team ASP.NET MVC Introduction
JavaScript: ExpressJS Overview
Presentation transcript:

Working with Data Model Binders, Display Templates, Editor Templates, Validation… SoftUni Team Technical Trainers Software University

2 1.Scaffolding 2.Model Binders 3.Display & Editor Templates 4.Data Validation 5.Session, TempData 6.Working with Data Source  Repository Design Pattern  Unit of Work Design Pattern  Ninject IoC and AutoMapper Table of Contents

Scaffolding

4  Code generation framework for ASP.NET  When you want to quickly add boilerplate code that interacts with data models  Enhances developer productivity  Can reduce the amount of time to develop standard data operations in your project  Enables customization  Provides an extensibility mechanism to customize generated code  VS 2015 includes pre-installed code generators for MVC and Web API What is ASP.NET Scaffolding?

Demo: Creating a Scaffold Creating CRUD pages with read/write actions, using Entity Framework

Model Binders

7  Make handling HTTP post requests easier  Assist in populating the parameters in action methods Model Binders DefaultModelBinder

8  Parameter binding  The name attribute of the HTML input element should be the same as the name of the action parameter Model Binders

9  Object binding  The model binder will try to "construct" the object based on the name attributes on the input HTML elements Model Binders

10  Binding nested objects  Use name attributes as following " {obj}.{nestedObj} "  Or use EditorFor() Model Binders

11  Binding a collection of primitive types  Use the same name attribute on every input element and the parameter name of the collection in the action (you can use loops) Model Binders

12  Binding a collection of objects  Use name attributes like " [{index}].{property} "  Or use EditorFor in a for loop Model Binders

13  Binding a collection of files  Use the same name attribute on all input type files as the name of the collection Model Binders

14 Custom Model Binder

Display & Editor Templates

16  ASP.NET MVC comes with helper methods  DisplayFor(), DisplayForModel()  EditorFor(), EditorForModel()  There are default implementations  Can be configured easily  Create folders "DisplayTemplates" and "EditorTemplates" in the “Views/Shared" folder or in the "Views/{Controller}" folder Templates

17  In the two new folders create a view for each type you want  The file name must be the same as the type name  string -> String.cshtml  int -> Int32.cshtml  DateTime -> DateTime.cshtml  Student -> Student.cshtml  The name of the files must reflect the data types and in them Custom Templates

18  The display / editor templates are normal view files  The framework will start using them instead of the default implementations  Example – String.cshtml  All strings will be in paragraph element and will have quotes surrounding them  DisplayFor(), EditorFor() - for properties in the model  DisplayForModel(), EditorForModel() – for the entire model Custom Templates

19  Passing additional information to the templates  There is an object " additionalViewData " which can be passed as parameter in the helper methods  You can pass anything there as anonymous type  And get the values from the ViewData / ViewBag Custom Templates

20  Sometimes you need two templates for one data type  Create the template with custom name  Decorate the property in the model with the [UIHint] attribute specifying the template name  You can set the name in the helpers too Custom Template Name

Data Validation

22  Attributes are defined in  System.ComponentModel.DataAnnotations  Covers common validation patterns  Required  StringLength  Regex  Range Validation with Annotations

23 Data Validation Attributes AttributeDescription RequiredChecks whether a non-null value is assigned to the property. It can be configured to fail if an empty string is assigned. StringLengthChecks whether the string is longer than the specified value. CompareChecks whether two specified properties in the model have the same value. RangeChecks whether the value falls in the specified range. It defaults to numbers, but it can be configured to consider a range of dates, too. RegularExpressionChecks whether the value matches the specified expression. EnumDataTypeChecks whether the value can be matched to any of the values in the specified enumerated type. CustomValidationChecks the value against the specified custom function. RemoteMakes an AJAX call to the server, and checks whether the value is acceptable.

24  Custom attributes  Inherit ValidationAttribute Custom Validation

25  ModelState.IsValid will give us information about the data validation success  ModelState.AddModelError() will produce a custom error Validating Model – Controller

26 – output errors – outputs validation message for specified property Validating Model – View Text box with integrated client-side validation jQuery validation library required for unobtrusive JavaScript validation P.S. Check Web.config

27  Your model should implemented IValidatableObject  From now on, MVC (works with EF too) will validate the object by your custom rules Class-Level Model Validation

Other Annotations

29 Display / Edit Annotations AttributeDescription UIHintSpecify the name of the template to use for rendering. DisplayNameFriendly name for labels DisplayFormatFormat strings and null display text DisplayColumnSpecify the property of a model class for simple text display. ReadOnlySpecify a read-only property (for model binding). HiddenInputRender value in a hidden input (when editing). ScaffoldColumnTurn display and edit capabilities on / off BindTells the model binder which properties to include/exclude

Session, TempData, Cache

31  Each client has session id, which ASP.NET stores  You can use it to store information in the memory of the application Session

32  TempData can be used like a dictionary  Each saved value lasts for the current and the next request  Perfect for redirects TempData

33  You can save global data into the Cache  It works like dictionary  It is not per client, but rather global Cache

Working with Data Sources Repository and Unit of Work

35  Separate business code from data access  Separation of concerns  Testability  Encapsulate data access  Increased level of abstraction  More classes, less duplicated code  Maintainability, Flexibility, Testability  Generic repositories  IRepository Repository Design Pattern

36 Repository Pattern (2) Business & Domain Logic SQL Database File Web Service Exchange Rates Repository Blog Posts Repository Settings Repository

37  Track changes in persistent objects  Efficient data access  Manage concurrency problems  Manage transactions  Keep business logic free of data access code  Keep business logic free from tracking changes  Allow business logic to work with logical transactions Unit of Work

38 Repository and UoW Patterns in an ASP.NET MVC  Source: torials/getting-started-with- ef-using-mvc/implementing- the-repository-and-unit-of- work-patterns-in-an-asp- net-mvc-application torials/getting-started-with- ef-using-mvc/implementing- the-repository-and-unit-of- work-patterns-in-an-asp- net-mvc-application

39  You may want to use IoC for dependency inversion  Ninject is quite easy to do  Install Ninject.MVC5 from NuGet  In App_Data/NinjectWebCommon add your bindings in RegisterServices() method Ninject IoC

40  You may want to use AutoMapper to map your database models to ViewModels for the web  Install AutoMapper from NuGet  Make mappings for the models  Use them in your LINQ queries  Check the documentation  AutoMapper

? ? ? ? ? ? ? ? ? Working with Data

SoftUni Diamond Partners

License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 43  Attribution: this work may contain portions from  "ASP.NET MVC" course by Telerik Academy under CC-BY-NC-SA licenseASP.NET MVCCC-BY-NC-SA

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg