38
ASP.NET MVC Part I Ventsislav Popov Microsoft academy.telerik.com Developer Evangelist ventsypopov.com mvccourse.telerik.com

17. ASP.NET-MVC - ASP.NET MVC

Embed Size (px)

DESCRIPTION

Web Applications with ASP.NET MVC @ Telerik Academy http://mvccourse.telerik.com The website and all video materials language is Bulgarian This lecture discusses the following topics: Beforehand – ASP.NET Web Forms What is MVC What is ASP.NET MVC? Models Views Controllers Validation Routing Unit Tests View engines

Citation preview

Page 1: 17. ASP.NET-MVC - ASP.NET MVC

ASP.NET MVC Part I

Ventsislav Popov

Microsoftacademy.telerik.com

Developer Evangelist ventsypopov.com

mvccourse.telerik.com

Page 2: 17. ASP.NET-MVC - ASP.NET MVC

Agenda Beforehand – ASP.NET Web Forms What is MVC What is ASP.NET MVC? Models Views Controllers Validation Routing Unit Tests View engines

2ventsypopov.

com

Page 3: 17. ASP.NET-MVC - ASP.NET MVC

ASP.NET Web Forms Rich controls and tools Postbacks Event driven web development Viewstate Less control over the HTML Hard to test Rapid development

3ventsypopov.

com

Page 4: 17. ASP.NET-MVC - ASP.NET MVC

Let’s chat for a bit…

4ventsypopov.

com

Page 5: 17. ASP.NET-MVC - ASP.NET MVC

What is MVC

5

Page 6: 17. ASP.NET-MVC - ASP.NET MVC

Model – View - Controller

6

Controller - responsible for handling all user input

Model - represents the logic of the application

View - the visual representation of the model

ventsypopov.

com

Page 7: 17. ASP.NET-MVC - ASP.NET MVC

ASP.NET MVC More control over HTML No Codebehind Separation of concerns Easy to test URL routing No postbacks No ViewState

7ventsypopov.

com

Page 8: 17. ASP.NET-MVC - ASP.NET MVC

Models The model should contain all of the

application business logic, validation logic, and database access logic.

ASP.NET MVC is compatible with any data access technology (for example LINQ to SQL)

All .edmx files, .dbml files etc. are located in the Models folder.

8ventsypopov.

com

Page 9: 17. ASP.NET-MVC - ASP.NET MVC

Custom View Models

9

When you combine properties to display on a View

namespace ContosoUniversity.ViewModels{ public class AssignedCourseData { public int CourseID { get; set; } public string Title { get; set; } public bool Assigned { get; set; } }}

ventsypopov.

com

Page 10: 17. ASP.NET-MVC - ASP.NET MVC

Creating a Model - DEMO

10

ventsypopov.

com

Page 11: 17. ASP.NET-MVC - ASP.NET MVC

What is Controller? It is a class Derives from the base

System.Web.Mvc.Controller class Generates the response to the

browser request

11

public class HomeController : Controller{ public ActionResult Index() { ViewBag.Message = "Welcome to ASP.NET MVC!";

return View(); }

public ActionResult About() { return View(); }}

ventsypopov.

com

Page 12: 17. ASP.NET-MVC - ASP.NET MVC

Controller Actions Public method of the Controller

class Cannot be overloaded Cannot be a static method Returns action result

12

public ActionResult About(){

return View();}

ventsypopov.

com

Page 13: 17. ASP.NET-MVC - ASP.NET MVC

Action Results Controller action response to a

browser request Inherits from the base

ActionResult class Different results types

13

ventsypopov.

com

Page 14: 17. ASP.NET-MVC - ASP.NET MVC

Implement a Controller - DEMO

14

ventsypopov.

com

Page 15: 17. ASP.NET-MVC - ASP.NET MVC

Action Results Types ViewResult EmptyResult RedirectResult JsonResult JavaScriptResult ContentResult FileContentResult FileStreamResult FilePathResult

15

ventsypopov.

com

Page 16: 17. ASP.NET-MVC - ASP.NET MVC

Controller base class methods View

Redirect RedirectToAction RedirectToRoute Json JavaScriptResult Content File

16

ventsypopov.

com

Page 17: 17. ASP.NET-MVC - ASP.NET MVC

Views Most of the Controller Actions

return views The path to the view is inferred

from the name of the controller and the name of the controller action. \Views\ControllerName\

ControllerAction.aspx A view is a standard (X)HTML

document that can contain scripts. script delimiters <% and %> in the

views 17

ventsypopov.

com

Page 18: 17. ASP.NET-MVC - ASP.NET MVC

Pass Data to a View With ViewData:

ViewData["message"] = "Hello World!";

Strongly typed ViewData: ViewData.Model = OurModel;

With ViewBag:

ViewBag.Message = "Hello World!";

18

ventsypopov.

com

Page 19: 17. ASP.NET-MVC - ASP.NET MVC

Post data to a controller Verb Attributes

The action method in the controller accepts the values posted from the view.

The view form fields must match the same names in the controller.

19

ventsypopov.

com

[HttpPost]public ActionResult Edit(Movie movie){

if (ModelState.IsValid){

db.Entry(movie).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index");

}return View(movie);

}

Page 20: 17. ASP.NET-MVC - ASP.NET MVC

Explore a View - DEMO

20

ventsypopov.

com

Page 21: 17. ASP.NET-MVC - ASP.NET MVC

HTML Helpers Methods which typically return

string. Used to generate standard HTML

elements textboxes, dropdown lists, links etc. Example: Html.TextBox() method

Usage is optional You can create your own HTML

Helpers

21

ventsypopov.

com

Page 22: 17. ASP.NET-MVC - ASP.NET MVC

Validation Two types of validation error

messages generated before the HTML form

fields are bound to a class generated after the form fields are

bound to the class Model State Validation Helpers

Html.ValidationMessage() Html.ValidationSummary()

22

ventsypopov.

com

Page 23: 17. ASP.NET-MVC - ASP.NET MVC

Implement validation- DEMO

23

ventsypopov.

com

Page 24: 17. ASP.NET-MVC - ASP.NET MVC

Routing The Routing module is responsible

for mapping incoming browser requests to particular MVC controller actions.

Two places to setup: Web.config file Global.asax file

24

ventsypopov.

com

Page 25: 17. ASP.NET-MVC - ASP.NET MVC

Routing Setup Web.config file

25

<system.web><httpModules>

<system.web><httpHandlers>…

<system.webServer> <modules> …

<system.webServer> <handlers> …

ventsypopov.

com

Page 26: 17. ASP.NET-MVC - ASP.NET MVC

Routing SetupGlobal.asax file

26

public class MvcApplication : System.Web.HttpApplication{

public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home",

action = "Index", id = "" } );

}

protected void Application_Start() { RegisterRoutes(RouteTable.Routes); }}

ventsypopov.

com

Page 27: 17. ASP.NET-MVC - ASP.NET MVC

URL Example

http://www.mysite.com/Home/About/6

{controller} = Home {action} = About {id} = 6

27

ventsypopov.

com

ventsypopov.

com

Page 28: 17. ASP.NET-MVC - ASP.NET MVC

Routing example - DEMO

28

ventsypopov.

com

Page 29: 17. ASP.NET-MVC - ASP.NET MVC

Unit Tests Used for the business logic (not

DAL or View logic). Test individual “unit”of code Make the code safe to modify Mock Object framework

When you lack “real” objects Create mocks for the classes in the

application Test with mock objects

29

ventsypopov.

com

Page 30: 17. ASP.NET-MVC - ASP.NET MVC

Unit Tests - DEMO

30

ventsypopov.

com

Page 31: 17. ASP.NET-MVC - ASP.NET MVC

View Engines Handles the rendering of the view

to UI (html/xml); Different view engines have

different syntax ASP.NET MVC 3 Pre-included View

Engines: Web Forms Razor

31

ventsypopov.

com

Page 32: 17. ASP.NET-MVC - ASP.NET MVC

View Engines - DEMO

32

ventsypopov.

com

Page 33: 17. ASP.NET-MVC - ASP.NET MVC

Things to remember What MVC stands for How ASP.NET MVC differs from Web

Forms Where is routing configured How to validate business logic How to use helpers Unit tests basics Choice between “View Engines”

33

ventsypopov.

com

Page 34: 17. ASP.NET-MVC - ASP.NET MVC

Useful sites http://www.asp.net/mvc http://msdn.microsoft.com/en-us/li

brary/dd394709.aspx http://stackoverflow.com/ http://jquery.com/

34

ventsypopov.

com

Page 35: 17. ASP.NET-MVC - ASP.NET MVC

ASP.NET MVC

ventsypopov.

com

Email: vepopov [at] microsoft.comTwitter: @v_popov

Page 36: 17. ASP.NET-MVC - ASP.NET MVC

Time to wake up :)

36

Page 37: 17. ASP.NET-MVC - 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 MVC Part I

http://academy.telerik.com

Page 38: 17. ASP.NET-MVC - ASP.NET MVC

Free Trainings @ Telerik Academy

Web Applications with ASP.NET MVC Course mvccourse.telerik.com

Telerik Software Academy academy.telerik.com

Telerik Academy @ Facebook facebook.com/TelerikAcademy

Telerik Software Academy Forums forums.academy.telerik.com