ASP NET MVC Mait Poska Andres Kver IT
- Slides: 52
ASP. NET MVC Mait Poska & Andres Käver, IT Kolledž 2014 1
Projekt – paneme kõik kokku kontaktihaldus Loo uus C# ASP. NET MVC 5 Web Application. • Vali sobivad nimed web projectile ja solutionile (Contact. App. MVC ja Contact. Solution) • Tõmba alla kõik Nu. Get’i uuendused • 2
Projekt – algvalikud 3
Projekt – model ja repo • • • Loo eraldi projektid domeenimudeli ja repositoorumite jaoks Hiire parem klikk Solutioni peal ja Add -> New Project. . . Tüübiks Visual C# Class Library Domeenimudelid – Contact. Models Data Access Layer – Contact. DAL 4
Projekt – model ja repo 5
EF Referentsid • • • Hiire parem klikk Solutioni peal ja Manage Nu. Get Packages for Solution Installed packages ja Entity. Framework Nupp Manage Lülitage Entity. Framework sisse Mudelis ja DAL’is, välja veebiprojektis F 6 kompileerib kogu lahenduse. Eemaldage veebiprojektist kõik kontodega seotu – kuni lahendus kompileerub vigadeta. 6
EF Referenstid 7
Mudeli ja repo testimine - konsool Lisa ka konsoolirakendus kiireteks testideks • Visual C# Console Application • 8
Kirjeldame domeenimudelid namespace Contact. Models { public class Person { public int Person. ID { get; set; } public String First. Name { get; set; } public String Last. Name { get; set; } public virtual List<Contact> Contacts { get; set; } } Contact. ModelsModels. cs public class Contact. Type { public int Contact. Type. ID { get; set; } public String Name { get; set; } public virtual List<Contact> Contacts { get; set; } } public class Contact { public int Contact. ID { get; set; } public int Contact. Type. ID { get; set; } public virtual Contact. Type { get; set; } public String Value { get; set; } public int Person. ID { get; set; } public virtual Person { get; set; } } } 9
DAL - Contact. Context namespace Contact. DAL { Contact. DALContact. Context. cs public class Contact. Context : Db. Context { public Db. Set<Person> People { get; set; } public Db. Set<Contact> Contacts { get; set; } public Db. Set<Contact. Type> Contact. Types { get; set; } public Contact. Context() : base("name=Contact. Context") //connectionstring { Database. Set. Initializer(new System. Data. Entity. Drop. Create. Database. If. Model. Changes<Contact. Context>()); } protected override void On. Model. Creating(Db. Model. Builder model. Builder) { } } } 10
DAL – Repo - Interface Contact. DALContact. Repo. cs public interface IEntity. Repository<T> : IDisposable { IQueryable<T> All { get; } IQueryable<T> All. Including(params Expression<Func<T, object>>[] include. Properties); T Find(int id); void Insert. Or. Update(T entity); void Delete(int id); void Save(); } public interface IPerson. Repository : IEntity. Repository<Person> { } 11
public class Person. Repository : IPerson. Repository { Contact. Context context = new Contact. Context(); public IQueryable<Person> All{ get { return context. People; } } DAL – Person. Repository Contact. DALContact. Repo. cs public IQueryable<Person> All. Including(params Expression<Func<Person, object>>[] include. Properties){ IQueryable<Person> query = context. People; foreach (var include. Property in include. Properties) { query = query. Include(include. Property); } return query; } public Person Find(int id){ return context. People. Find(id); } public void Insert. Or. Update(Person person){ if (person. Person. ID == default(int)){ // New entity context. People. Add(person); } else{ // Existing entity context. Entry(person). State = Entity. State. Modified; } } public void Delete(int id){ var person = context. People. Find(id); context. People. Remove(person); } public void Save(){ context. Save. Changes(); } public void Dispose(){ context. Dispose(); } } 12
Konsoolirakendus Connection. String • App. Config <? xml version="1. 0" encoding="utf-8" ? > <configuration> <startup> <supported. Runtime version="v 4. 0" sku=". NETFramework, Version=v 4. 5" /> </startup> <connection. Strings> <add name="Contact. Context" connection. String="Data Source=(Local. Db)v 11. 0; Initial Catalog=Contact. Base; Integrated Security=SSPI" provider. Name="System. Data. Sql. Client" /> </connection. Strings> </configuration> 13
Konsoolirakendus class Program { static void Main(string[] args) { using (var repo = new Person. Repository()) { repo. Insert. Or. Update(new Person { First. Name = "Juku", Last. Name = "Mänd" }); repo. Insert. Or. Update(new Person { First. Name = "Malle", Last. Name = "Tamm" }); repo. Save(); foreach (var person in repo. All. To. List()) { Console. Write. Line("{0} {1}", person. First. Name, person. Last. Name); } } Console. Read. Line(); } } 14
Andmebaas 15
No lõpuks teeme veebi kah • Repode kasutamiseks peab olema seadistatud Connection. String Web. config’us <? xml version="1. 0" encoding="utf-8"? > <configuration> <config. Sections>. . </config. Sections> <connection. Strings> <add name="Contact. Context" connection. String="Data Source=(Local. Db)v 11. 0; Initial Catalog=Contact. Base; Integrated Security=SSPI" provider. Name="System. Data. Sql. Client" /> </connection. Strings> 16
Model, View, Controller Domeenimudel – kogu äriloogika ja selle püsivus (persistence) • Vaated – šabloon/makett (template) andmete kuvamiseks • Kontroller – suhtlus äriloogika, vaadete ja kasutaja vahel • • View. Model – mudelid, mis käigus ainult veebirakendusesiseselt. Kasutusel komplekssete (tugevalt tüübitud) andmete edastamiseks vaadetele. 17
Controller • http: //localhost: xxxx/Home/About 18
Controller • • • Routing määrab, milline kontroller ja milline meetod sellest kontrollerist välja kutsutakse http päringu peale Routing defineeritakse failis App_StartRoute. Config. cs Standard: kontrollerinimi/meetodinimi/id. com/Clients/Edit/789 routes. Map. Route( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = Url. Parameter. Optional } ); namespace Contact. Web. Controllers { public class Home. Controller : Controller { public Action. Result About() { View. Bag. Message = "Your app description page. "; return View(); } 19
Controller – custom route public static void Register. Routes(Route. Collection routes) {. . . routes. Map. Route( "Test", "Test/{name}", new { controller = "Home", action = "Test. Action", name = "Default. Name" }); routes. Map. Route( name: "Default", . . . } public class Home. Controller : Controller { public Action. Result Test. Action(String name) { return Content(name); } 20
Controller - parameetrid Meetodi signatuuris kirjeldada parameetrid • Asp. net MVC raamistik üritab need väärtustada igal võimalikul viisil • Routing infost, get ja post parameetritest • public Action. Result Test. Action(String name, String second. Name) { return Content(name+": : "+second. Name); } 21
Controller – info tagastamine • Kõige lihtsam Hello. World using System; using System. Collections. Generic; using System. Linq; using System. Web. Mvc; namespace Contact. Web. Controllers { public class Home. Controller : Controller { public string Hello. World() { return "Hello, world!"; } 22
Controller – view (vaate) tagastamine public Action. Result Hello. View() { return View(); } ~/Views/Home/Hello. View. aspx ~/Views/Home/Hello. View. ascx ~/Views/Shared/Hello. View. aspx ~/Views/Shared/Hello. View. ascx ~/Views/Home/Hello. View. cshtml ~/Views/Home/Hello. View. vbhtml ~/Views/Shared/Hello. View. cshtml ~/Views/Shared/Hello. View. vbhtml Vaikimisi vaate võimalikud nimed! 23
Controller - Action. Result Nimi Raamistiku käitumine Meetod Content. Result Tagastab sõne Content Empty. Result Ei tagasta midagi File. Content. Result File. Path. Result File. Stream. Result Faili sisu Http. Unauthorized. Result HTTP 403 staatus Java. Script. Result Script käivitamiseks Java. Script Redirect. Result JSON formaadis data Json Redirect. To. Result Ümbersuunamine uuele URLile Redirect. To. Route. Result Ümbersuunamine teisele meetodile või kontroller/meetodile Redirect. To. Route Redirect. To. Action View. Result Partial. View. Result Tagastuse eest hoolitseb View. Engine View / Partial. View File 24
Controller – Action Selectors • • Action. Name Võimaldab üle kirjutada, millist urli Action. Name’i oodatakse Accept. Verbs Http. Post, Http. Get (put, delete, jne. . . ) Sama nimega action meetod erineva httprequesti teenindamiseks (signatuur peab erinema) [Action. Name("Tere. Maailm")] [Http. Get] public Action. Result Hello. View() { return View(); } [Action. Name("Tere. Maailm")] [Http. Post] public Action. Result Hello. View(int Id) { //do something here with post return View(); } http: //localhost/Home/Tere. Maailm 25
Controller – Action Filters Nimi Kirjeldus Output. Cache Puhverda kontrolleri väljundit Validate. Input(false) Lülita päringute valideerimine välja ja luba kontrollimatuid sisendeid (xss) Authorize Piira kasutust ainult mingitele kasutajatele või kasutajarollidele Validate. Anti. Forgery. Token Cross. Site võltspäringute vastu võitlemine Handle. Error Renderda see vaade, kui juhtub tulema käsitlemata exception 26
Controller – Action Filters • Action/Controller - Authorize [Authorize(Roles="Admin")] public string Hello. World() { return "Hello, world!"; } [Authorize(Users="akaver, mposka")] public string Hello. World() { return "Hello, world!"; } [Authorize] public class Home. Controller : Controller { public string Hello. World() { return "Hello, world!"; } 27
Controller – Global Filters • • /App_Start/Filter. Config. cs Globaalne filter töötab üle kõikide päringute namespace Contact. Web { public class Filter. Config { public static void Register. Global. Filters(Global. Filter. Collection filters) { filters. Add(new Handle. Error. Attribute()); } } } 28
Filter - Handle. Error. Attribute • Tõrke korral annab kliendile ilusa veateate public string Hello. World() { throw new Exception("Kohutav viga!!"); return "Hello, world!"; } Yellow Screen of Death! 29
Filter - Handle. Error. Attribute Vaikimisi antakse „ilus“ veateade ainult remote kliendile • Vajab natuke seadistamist /Web. config Vaikimisi väärtus on Remote. Only • ViewsSharedError. cshtml • <system. web> <custom. Errors mode="On"/> 30
Filter - Custom • FiltersLog. Attribute. cs namespace Contact. Web. Filters { public class Log. Attribute : Action. Filter. Attribute { public override void On. Action. Executed(Action. Executed. Context filter. Context) { base. On. Action. Executed(filter. Context); } } } using Contact. Web. Filters; namespace Contact. Web. Controllers { [Log] public class Home. Controller : Controller { public string Hello. World() { return "Hello, world!"; } 31
VIEW • • • Template + Data = Generated Output 32
<div> @Model. First. Name </div> <div> @Model. Last. Name, child of @Model. Father. Name </div var model = new {Name = „John“, Last. Name = „Doe“, Father. Name=„Mike“} return View(model); <div> John </div> <div> Doe, child of Mike </div 33
View Vaated asuvad kataloogis /Views/Controller. Name/ <Action. Name>. cshtml • Vaikimisi valitakse vaade kontrollerinime ja action meetodi nime põhjal • Konkreetse vaate valik: return View("My. Special. Secret. View"); • 34
View • Lisame uue vaate ViewsHome kataloogil hiire parem klikk ja Add->View. . . @{ View. Bag. Title = "Hello. View"; } <h 2>Hello, World!</h 2> 35
View – kust tuli kogu layout? • Esimesena laetakse sisse Views_View. Start. cshtml @{ Layout = "~/Views/Shared/_Layout. cshtml"; } • _Layout. cshtml’is on kogu weebi standardlayout. Konkreetne vaade lisatakse siin: <section class="content-wrapper main-content clear-fix"> @Render. Body() </section> 36
Razor viewengine • • • Segu staatilisest HTMList ja C#’ist C# osa algab @ märgiga Lõpu leiab Razor enamasti ise ja lülitub ümber HTMLi peale tagasi! Minimaalne kogus C# koodi vaadetes! Vaikimisi on kogu väljund HTMLkodeeringus (xss kaitse) 37
Razor expressions @muutuja • @csharpmeetod(parameeter) • Rating: @model. rating / 10 Rating: 10 / 10 • Rating: @(model. rating / 10) Rating: 1 • 38
Razor code blocks @{ siia niipalju C# koodi kui vaja; veel koodi; } @foreach (var item in Model) { <tr> <td> @item. First. Name, @item. Last. Name </td> </tr> } @foreach (var item in Model) { Kala. Maja <- viga, pole C#! @: Kala. Maja <-väljundtekst <text>Kala. Maja</text> <-väljundtekst } 39
HTML Helpers • • • Teevad standardsete HTML-plokkide genereerimise lihtsaks. 2 versiooni – tugevalt tüübitud (. . For) ja mitte. Inputs Links Forms Validation messages @Html. Label. For @Html. Editor. For @Html. Validation. Mesage. For @Html. Action. Link 40
Andmete saatmine vaatele • • • Mittetüübitud vaade View. Bag (ja Temp. Data) on kasutusel info edastamiseks kontrollerist vaatesse Intellisense tuge ei paku! Kollektsiooni pandud objekte peate ise peast teadma public Action. Result Hello. View() { View. Bag. First. Name = "John"; View. Bag. Last. Name = "Doe"; return View(); } @{ View. Bag. Title = "Hello. View"; } <h 2>Hello, @View. Bag. First. Name @View. Bag. Last. Name</h 2> 41
Andmete saatmine vaatele – tugevalt tüübitud • Kontrollerist edastatakse vaatele mudel public Action. Result Hello. View() { var model = new Person { First. Name = "John", Last. Name = "Doe"}; return View(model); } • Vaates defineeritakse, millist mudelit vaade kasutab @model Contact. Models. Person @{ View. Bag. Title = "Hello. View"; } <h 2>Hello, @Model. First. Name @Model. Last. Name</h 2> 42
View. Model Kasutatakse juhul, kui vaates on vaja kasutada rohkem infot kui äriloogika otsesed objektid pakuvad • Tüüpiline kasutusjuht on kõikvõimalikud dropdown listid • Tugevalt tüübitud vaated on kohustuslikud! • 43
Kontrolleri lisamine Hiire parem klikk Controllers kaustal ja Add->Controller. . . • Lisame Person. Controller’i • Entity Frameworki ei kasuta – kasutame repot! • Template: MVC Controller with empty read/write actions • 44
Vaate lisamine (Index) • • • Kontrolleri lähtekoodis parem hiireklikk meetodi sees ja Add View. . . Vaate nimi tekib ise meetodi nimest, Intellisense! Create strongly typed view Valige sobiv mudel (refereerige eelnevalt oma mudeliprojekti) Scaffold template: List 45
@model IEnumerable<Contact. Models. Person> @{ View. Bag. Title = "Index"; } /Views/Person/Index. cshtml <h 2>Index</h 2> <p> @Html. Action. Link("Create New", "Create") </p> <table> <tr> <th> @Html. Display. Name. For(model => model. First. Name) </th> <th> @Html. Display. Name. For(model => model. Last. Name) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html. Display. For(model. Item => item. First. Name) </td> <td> @Html. Display. For(model. Item => item. Last. Name) </td> <td> @Html. Action. Link("Edit", new { id=item. Person. ID }) | @Html. Action. Link("Details", new { id=item. Person. ID }) | @Html. Action. Link("Delete", new { id=item. Person. ID }) </td> </tr> } </table> 46
Repo kasutamine kontrolleris • • • Initsialiseerida repo Pärida andmed Laadida andmed mudelisse ja edastada vaatele public class Person. Controller : Controller { // Initialize repo on controller creation private Person. Repository repo = new Person. Repository(); // // GET: /Person/ public Action. Result Index() { return View(repo. All. Order. By(p => p. Last. Name). To. List()); } 47
48
Details meetod // // GET: /Person/Details/5 public Action. Result Details(int id) { Person person = repo. Find(id); if (person == null) { return Http. Not. Found(); } return View(person); } 49
Create meetod // // GET: /Person/Create public Action. Result Create() { return View(); } // // POST: /Person/Create [Http. Post] public Action. Result Create(Person person) { if (Model. State. Is. Valid) { repo. Insert. Or. Update(person); repo. Save(); return Redirect. To. Action("Index"); } return View(person); } 50
Edit meetod // // GET: /Person/Edit/5 public Action. Result Edit(int id) { Person person = repo. Find(id); if (person == null) { return Http. Not. Found(); } return View(person); } // // POST: /Person/Edit/5 [Http. Post] public Action. Result Edit(Person person) { repo. Insert. Or. Update(person); repo. Save(); return View(person); } 51
Delete meetod // // GET: /Person/Delete/5 public Action. Result Delete(int id) { Person person = repo. Find(id); if (person == null) { return Http. Not. Found(); } return View(person); } // // POST: /Person/Delete/5 [Http. Post, Action. Name("Delete")] public Action. Result Delete. Confirmed(int id) { repo. Delete(id); repo. Save(); return Redirect. To. Action("Index"); } 52
- Asp.net tutorialspoint
- Asp.net mvc 5 identity authentication and authorization
- Classic asp to asp.net migration
- Veebruarirevolutsioon
- Custom controls in asp.net
- Introduction to asp.net
- Asp net feature flags
- Asp.net execution model
- 2160711
- Timeline asp.net
- Crud asp.net c# web forms
- Sql injection waf bypass payloads
- Asp.net core soap
- Asp.net
- 大阪 microsoft asp
- Asp.net agenda
- Asp net load testing
- Asp.net introduction
- 大阪 microsoft asp.net
- Client server architecture in asp net
- Asp net core future
- Azure bug bounty
- Desarrollo de aplicaciones web con asp.net
- Asp.net core 5 odata
- Asp.net server controls
- Reflection net
- Asp.net session management
- Agenda en asp.net
- Asp net session state
- Iis php
- Asp.net roadmap
- List (3) common reasons mvc rejects road test vehicles:
- Mvc paradigm
- Swing mvc example
- Trygve reenskaug mvc
- Action selectors in mvc
- Mvc m
- Java spring board
- Model layer in mvc
- Mvc mis
- Partial view
- O tero
- Gdl upgrade nj
- Que es struts
- Mvt vs mvc
- Jee mvc
- Mvc routing
- Mvc spencer
- Asdf service application 삭제
- Spring legacy project 없을때
- Mvc vs webforms
- Mvc muster
- Trygve reenskaug mvc