36
ASP.NET MVC Working with Data Telerik School Academy http://academy.telerik.com ASP.NET MVC

Telerik School Academy ASP.NET MVC

Embed Size (px)

Citation preview

Page 1: Telerik School Academy  ASP.NET MVC

ASP.NET MVCWorking with Data

Telerik School Academyhttp://academy.telerik.com

ASP.NET MVC

Page 2: Telerik School Academy  ASP.NET MVC

Table of Contents Scaffolding Model Binders Editor & Display Templates Data Validation

Annotation attributes

Session, TempDataand Cache

2

Page 3: Telerik School Academy  ASP.NET MVC

Scaffolding

Page 4: Telerik School Academy  ASP.NET MVC

What is ASP.NET Scaffolding?

Code generation framework for ASP.NET When you want to quickly add

boilerplate code that interacts with data models

Developer productivity enhancer 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 2013 includes pre-installed code generators for MVC, and Web API

4

Page 5: Telerik School Academy  ASP.NET MVC

Demo: Create ScaffoldCreate CRUD pages with read/write

actions, using Entity Framework

Page 6: Telerik School Academy  ASP.NET MVC

Model Binders

Page 7: Telerik School Academy  ASP.NET MVC

Model Binders To make easy of handling HTTP post request

Help the populating the parameters in action methods

7

HTTP POST /Review/Create

Rating=7&Body=Great!

DefaultModelBinder

Page 8: Telerik School Academy  ASP.NET MVC

Model Binders Parameter binding

The name attribute of the input HTML element should be the same as the name of pararameter in the action

8

Page 9: Telerik School Academy  ASP.NET MVC

Model Binders Object binding

Model binder will try to "construct" the object based on the name attributes on the input HTML elements

9

Page 10: Telerik School Academy  ASP.NET MVC

Model Binders Nested Objects binding

Use name attributes as following "{obj}.{nestedObj}" or use EditorFor

10

Page 11: Telerik School Academy  ASP.NET MVC

Model Binders Collection of primitive types binding Use the same name attribute on

every input element and the parameter name of the collection in the action (you can use loops)

11

Page 12: Telerik School Academy  ASP.NET MVC

Model Binders Collection of objects binding

Use name attributes like "[{index}].{property}" or use EditorFor in a for loop

12

Page 13: Telerik School Academy  ASP.NET MVC

Model Binders Collection of files binding

Use the same name attribute on all input type files as the name of the collection

13

Page 14: Telerik School Academy  ASP.NET MVC

Custom Model Binder

14

Page 15: Telerik School Academy  ASP.NET MVC

Display & Editor Templates

Page 16: Telerik School Academy  ASP.NET MVC

Templates ASP.NET MVC comes with helpers methods DisplayFor(), DisplayForModel()

EditorFor(), EditorForModel()

There are default implementation Easily to be configured Create folders "DisplayTemplates" and "EditorTemplates" the "Shared" folder or in the "Views/{Controller}" folder 16

Page 17: Telerik School Academy  ASP.NET MVC

Custom Templates

In the two new folders create a view for each type you want string -> String.cshtml

int -> Int32.cshtml

DateTime -> DateTime.cshtml

Student -> Student.cshtml

The name of the files must reflect the data types and the @model in them

17

Page 18: Telerik School Academy  ASP.NET MVC

Custom Templates These views are normal view files The framework will start using them instead of the default implementations

For example in the String.cshtml Now all strings will be in paragraphelement and will have quotes surrounding them

DisplayFor, EditorFor -> for properties

DisplayForModel, EditorForModel -> for model

18

Page 19: Telerik School Academy  ASP.NET MVC

Custom Templates

Passing additional information to the templates There is an object

"additionalViewData" in the helper methods as parameter

You can pass anything there as anonymous type

And get the values from the ViewData/ViewBag

19

Page 20: Telerik School Academy  ASP.NET MVC

Custom Template Name 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

20

Page 21: Telerik School Academy  ASP.NET MVC

Data Validation

Page 22: Telerik School Academy  ASP.NET MVC

Validation with Annotations

Attributes defined in System.ComponentModel.DataAnnotations

Covers common validation patterns Required

StringLength

Regex

Range

22

Page 23: Telerik School Academy  ASP.NET MVC

Data Validation Attributes

23

Attribute Description

Compare Checks whether two specified properties in the model have the same value.

CustomValidation

Checks the value against the specified custom function.

EnumDataType Checks whether the value can be matched to any of the values in the specified enumerated type.

Range Checks whether the value falls in the specified range. It defaults to numbers, but it can be configured to consider a range of dates, too.

RegularExpression

Checks whether the value matches the specified expression.

Remote Makes an Ajax call to the server, and checks whether the value is acceptable.

Required Checks whether a non-null value is assigned to the property. It can be configured to fail if an empty string is assigned.

StringLength Checks whether the string is longer than the specified value.

Page 24: Telerik School Academy  ASP.NET MVC

Validating Model – Controller

ModelState.IsValid – will give us information about the data validation success

ModelState.AddModelError – custom error

24

Page 25: Telerik School Academy  ASP.NET MVC

Validating Model – View @Html.ValidationSummary – output errors

@Html.ValidationMessageFor(…) – outputs validation message for specified property

25

Text box with integrated client-side validation

jQuery validation library required for unobtrusive JavaScript validation

Page 26: Telerik School Academy  ASP.NET MVC

Custom Validation Custom attributes Inherit ValidationAttribute

26

Page 27: Telerik School Academy  ASP.NET MVC

Class-Level Model Validation

Your model should implemented IValidatableObject

From now on, MVC (works with EF too) will validate the object by your custom rules

27

Page 28: Telerik School Academy  ASP.NET MVC

Other Annotations

Page 29: Telerik School Academy  ASP.NET MVC

Display / Edit Annotations

29

Attribute Description

DisplayColumn

Specify the property of a model class for simple text display.

HiddenInput Render value in a hidden input (when editing).

UIHint Specify the name of the template to use for rendering.

DataType Common templates (email, password, URL, currency)

ReadOnly Specify a read-only property (for model binding).

DisplayFormat

Format strings and null display text

ScaffoldColumn

Turn off display and edit capabilities

DisplayName Friendly name for labels

Bind Tells the model binder which properties to include/exclude

Page 30: Telerik School Academy  ASP.NET MVC

Session, TempData and Cache

Page 31: Telerik School Academy  ASP.NET MVC

Session

Each client has session id, which ASP.NET stores

You can use it to store information in the memory of the application

31

Page 32: Telerik School Academy  ASP.NET MVC

TempData TempData can be used like a dictionary

Each saved value lasts for the current and the next request

Perfect for redirects

32

Page 33: Telerik School Academy  ASP.NET MVC

Cache You can save global data into the Cache

It works like dictionary It is not per client, but rather global

33

Page 34: Telerik School Academy  ASP.NET MVC

форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно

програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки

уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop

уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC

безплатен курс "Разработка на софтуер в cloud среда"

BG Coder - онлайн състезателна система - online judge

курсове и уроци по програмиране, книги – безплатно от Наков

безплатен курс "Качествен програмен код"

алго академия – състезателно програмиране, състезания

ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NETкурсове и уроци по програмиране – Телерик академия

курс мобилни приложения с iPhone, Android, WP7, PhoneGap

free C# book, безплатна книга C#, книга Java, книга C#Дончо Минков - сайт за програмиранеНиколай Костов - блог за програмиранеC# курс, програмиране, безплатно

?

? ? ??

?? ?

?

?

?

??

?

?

? ?

Questions?

?

ASP.NET MVCWorking with Data

http://academy.telerik.com

Page 35: Telerik School Academy  ASP.NET MVC

Homework1. Create a simple ASP.NET MVC

Twitter-like system using data validation, Entity Framework, repository pattern and unit of work pattern. Your system should:

Have users and administrators List all tweets for specific user in

his profile List all tweets containing specific

tag (#fail) and use 15 minutes caching for each tag

Have administration for the tweets using ASP.NET scaffolding (admins only)

* Have Kendo UI Grid-based administration for tweets (with paging, sorting, filtering, etv.)

42

Page 36: Telerik School Academy  ASP.NET MVC

Free Trainings @ Telerik Academy

“C# Programming @ Telerik Academy csharpfundamentals.telerik.com

Telerik Software Academy academy.telerik.com

Telerik Academy @ Facebook facebook.com/TelerikAcademy

Telerik Software Academy Forums forums.academy.telerik.com 43