Question? Leave a message!


ASP .NET MVC 5 Nemanja Kojic, MScEE 1What is MVC • ModelViewController (MVC) • Standard Architectural Pattern • Separation of concerns: model, view, controller 2 of 114ASP .NET MVC Framework • An alternative to ASP .NET Web Forms • Presentation framework – Lightweight – Highly testable – Integrated with the existing ASP .NET features: • Master pages • MembershipBased Authentication • ... 3 of 114ASP .NET MVC Framework Components • Models – Business/domain logic – Model objects, retrieve and store model state in a persistent storage (database). • Views – Display application’s UI – UI created from the model data • Controllers – Handle user input and interaction – Work with model – Select a view for rendering UI 4 of 114When to use MVC approach • Advantages: – Easier to manage complexity (divide and conquer) – It does not use server forms and view state – Front Controller pattern (rich routing) – Better support for testdriven development – Ideal for distributed and large teams – High degree of control over the application behavior 5 of 114ASP .NET MVC Features • Separation of application tasks – Input logic, business logic, UI logic • Support for testdriven development – Unit testing – No need to start app server • Extensible and pluggable framework – Components easily replaceable or customized (view engine, URL routing, data serialization,…) 6 of 114ASP .NET MVC Features (cont.) • Support for Dependency Injection (DI) – Injecting objects into a class – Class doesn’t need to create objects itself • Support for Inversion of Control (IOC) – If an object requires another object, the first should get the second from an outside source (configuration file) 7 of 114ASP .NET MVC Features (cont.) • Extensive support for ASP .NET routing • Building apps with comprehensible and searchable URLs • Customizable URLs – Adapted to work well with search engines – Adapted to REST addressing – Decoupled from resource files • Use of existing ASP .NET features (backward compatibility) 8 of 114ASP .NET MVC App Structure • URLs mapped to controller classes • Controller – handles requests, – executes appropriate logic and – calls a View to generate HTML response • URL routing – ASP .NET routing engine (flexible mapping) – Support for defining customized routing rules – Automatic passing/parsing of parameters 9 of 114ASP .NET App Structure • No Postback interaction • All user interactions routed to a controller • No view state and page lifecycle events 10 of 114MVC App Execution • Entry points to MVC: – UrlRoutingModule and MvcRouteHandler • Request handling: – Select appropriate controller – Obtain a specific controller instance – Call the controller’s Execute method 11 of 114MVC App Execution stages • Receive first request for the application – Populating RouteTable • Perform routing • Create MVC Request handler • Create controller • Execute controller • Invoke action • Execute result – ViewResult, RedirectToRouteResult, ContentResult, FileResult, JsonResult, RedirectResult 12 of 114MVC App Execution 13 of 114BUILDING VIEW PAGES USING RAZOR LANGUAGE RAZOR ENGINE 14 of 114Razor Engine • A new viewengine • Optimized around HTML generation • Codefocused templating approach 15 of 114Razor Engine – Design goals • Compact, Expressive and Fluid • Easy to learn • It is not a new language • Works with any text editor • Great Intellisense • Unittestable – Testing views without server, controllers… 16 of 114Razor – HelloWorld • Uses for razor file Razor blocks .aspx file 17 of 114Loops and Nested HTML Razor syntax .aspx syntax 18 of 114If Blocks and Multiline Statements MultiToken IF statement statement Variables can span Multiline Variables multiple server statement code blocks 19 of 114Integrating Content and Code Parser examines righthand side of character. Identifying nested content with HTML block tag 20 of 114Layout/Master page SiteLayout.cshtml RenderBody() Including specific body content. 21 of 114Content page Explicitly setting LayoutPage property. Complete HTML page. 22 of 114Master page – section overrides This section is optional. This section is optional. 23 of 114Master page – section overrides Named section. Named section. 24 of 114Master page – result html 25 of 114Reusable “HTML Helpers” • Methods that can be invoked within codeblocks • Encapsulate generating HTML • Implemented using pure code • Work with Razor engine Builtin HTML helper 26 of 114Define own HTML helpers helper Helper’s parameters (full declarative syntax language and ebugging support) HTML Helper definition HTML Helper should be placed to Views\Helper directory. HTML Helper Invocation 27 of 114Visual Studio support 28 of 114Razor – Summary • A good new view engine • Codefocused templating • Fast and expressive • Compact syntax • Integrated with C and VB 29 of 114CREATING ASP .NET MVC APPLICATION 30 of 114New Project … 3132 of 114Select the project template 33ASP .NET MVC App Home page 34Run the application… 35Expand the default App menu 36ADDING CONTROLLER 37 of 114Adding controller 38Adding controller (cont.) 39Adding a controller (cont.) 40Testing the controller 41Mapping controller • Controller selection based on URL • Default URL routing logic: /Controller/ActionName/Parameters • Format for routing in AppStart/RouteConfig.cs 42 of 114URL routing • Webapp URL without URL segments = HomeController::Index() • Index() – default method of a controller • /HelloWorld = HelloWorldController • /HelloWorld/Index = HelloWorldController::Index() • http://webapp:port/HelloWorld/Welcome = HelloWorldController::Welcome() 43 of 114Parameters • /HelloWorld/Welcomename=Scottnumtimes=4 • Introducing 2 parameters to Welcome method • Parameters passed as query strings 44 of 114URL Parameters • http://webapp/HelloWorld/Welcome/3name=Rick Parameter ID matches URL specification in RegisterRoutes method. 45 of 114ADDING A VIEW 46 of 114Views • Views created using Razor view engine • Controller method returns View object • Controller method return type is ActionResult • Common pattern: all view pages share the same master layout page 47 of 114Create View page 48 of 114Create View page Master page. 49 of 114Implementing View page Index, by default. Selected master page. Change controller’s method signature. The method retures a view object: searches a view file that is named the 50 of 114 same as the method (Index.cshtml).ViewBag • Pass data between view template and layout view file • ViewBag is a dynamic object (has no defined properties) View template file. Layout view file. 51 of 114Passing data from Controller to View • View is used for data presentation • Controller must provide a view with the data • One approach: using ViewBag – Controller puts data to ViewBag, – View reads ViewBag and renders the data – No data binding • Alternative approach: the view model – Strongly typed approach 52 of 114Passing data from Controller to View Controller View Returns HelloWorldView object. 53 of 114ADDING A MODEL 54 of 114Model components • Entity framework data access technology • “Code first” development paradigm (first code classes, then generate DB schema) • “Database first” development paradigm define db schema first, then generate models, controllers and views 55 of 114Adding a model class Enter the class name, e.g. Movie.cs 56 of 114Adding properties to a model class 57 of 114Adding a DbContext class EF namespace DbContext DbSet EF database context FETCH, INSERT, UPDATE 58 of 114DB Connection string Separate connection string for each DbContex class 59 of 114Accessing Model from a Controller 60 of 114Accessing Model from a Controller Visual Studio Creates: Strongly typed A controller MoviesController.cs approach. file in Controllers folder, Create.cshtml, Delete.cshtml, Details.cshtml, Index.cshtml in Views\Movies folder. 61 of 114Run Application… Notice: default routing Creates a new movie. Notice: generic column Database is still empty. name, derived from the model class. 62 of 114Creating a model object Automatically generated form, based on the model info. 63 of 114Generated Controller class Instantiated DbContext instance. Index method. 64 of 114Strongly typed models • MVC provides strongly typed way of passing data from Controller to View • Better compiletime checking • Richer IntelliSense in VS code editor 65 of 114Strongly typed models model: Specifies class of the model Communicates with the master page. Id parameter generally passed as a part of the route. Contextsensitive data access. 66 of 114Strongly typed models (cont.) Index.cshtml Model object is strongly typed. Each item is a Movie object. Full compiletime support. 67 of 114Edit View Localhost:1234/movies/Edit/4 URL generated using Html Helpers 68 of 114Edit View (cont.) Parameter passed through the URL query. Works for MVC default URL mapping. Label defined in the Date format defined in model class. the model class. 69 of 114Edit View Generates hidden antiforgery token. Generates html label. Generates text box. Generates validation message. 70 of 114Property annotations Annotations namespace. Overrides default label name on the view page. Specifies type of the data: displays only date part. Workaround for a bug in Chrome  71 of 114ActionLink helper • Html.ActionLink – generates a link according to a given URL mapping policy Anonymous object – specifies ID of an object • Primer: Html.ActionLink(“Edit", “Edit", newid=item.ID) Controller action name. 72 of 114Edit actions • Implemented as Controller’s operations HTTP GET operation HTTP POST operation Prevents request forgery Bind attribute – a security mechanism that prevents overposting data to the model. HttpGet annotation by default. 73 of 114Processing the POST request HTTP POST method. Validates the forgery token. Checks if sent data are valid – server side validation, compared to clientside validation (javascript) Redirects after successful update. In case of invalid data, the original form is returned back to the client, displaying error messages 74 of 114HTTP methods – best practices • HttpGet and HttpPost method overloads • All methods that modify data SHOULD use HttpPost method overload • Modifying data in HttpGet method – security risk – Violates HTTP best practices – Violates REST architectural pattern • GET method SHOULD NOT have any side effect and SHOULD NOT modify persistent data 75 of 114ADDING SEARCH 76 of 114Search form – Index.cshtml Enter a text filtering value. 77 of 114View/Controller – changes Controller – changed signature of View (changes) the method Index. LINQ query definition (NOT execution) Default form Lambda expression method = POST Use overriden BeginForm method to force HttpGet method. 78 of 114Searching movies – URL query HTTP POST HTTP GET 79 of 114Adding search by Genre HttpGet method handles the request. 80 of 114Search by Genre – View Preselected value. DropDown list markup. Parameter “movieGenre” is the key for populating dropdown list from ViewBag. 81 of 114Search by Genre – Controller Key movieGenre is the Populating the same as the parameter list of genres in of the dropdown list. ViewBag. 82 of 114Details method Controller 83 of 114Delete method Controller Asp .net maps a segment of URL HttpGet method. to a method. Selects an objects and Attribute ActionName is returns Details page. necessary to provide valid URL routing. The same URL maps to different action methods, based on used HTTP method. RULE: Never use a HttpGet method HttpPost method. to modify the model. Deletes an object Opens security holes, having the given id. architecturally bad 84 of 114Data Validation • Keep Things DRY (Don’t Repeat Yourself) • Declarative validation rules in one place (Model class) – Regular expressions – Range validation – Length validation – NULL values validation – Data formatting • Validation rules enforced before saving changes to the database 85 of 114Validation rules – Model Several validation rules failed. 86 of 114Data Validation View Clientside validation: javascript (jQuery). Validation rules picked up from the model class annotations. Validation messages derived from the validation constraints in the model class. 87 of 114Data Validation – View (cont.) Validation message derived from the validation constraints specified for the given Property (Title) 88 of 114Data Validation Controller HttpGet method displays initial Create form. HttpPost method that does create a new object. Serverside data validation check. 89 of 114DataType attributes • Provide only hits for the view engine to format the data • Date, Time, PhoneNumber, EmailAddress,… • Automatic provision of type specific features e.g. “mailto: ...” link for EmailAddress • Do NOT provide any Validation (just presentation hints) 90 of 114DisplayFormat annotation • Used to explicitly specify format of the data • Example: redefining the default date format It is possible to specify validation properties in one line 91 of 114LAMBDA EXPRESSIONS 92 of 114Introduction • Expressions that use special syntax • Anonymous functions used as data (variables, fields, parameters, return values) • The anonymous functions are used to create delegates and expression trees • Lambda expressions particularly helpful for writing LINQ queries • Available from .NET 4.5 93 of 114Operator = • Interpreted as “goes to” • Used for declaring a lambda expression • The same priority as assignment (=) • Right associative operator • Separates the parameters and function body = Right side Left side An Empty parameter list An expression A formal parameter list A Statement list inside curly brackects. An implicit parameter list 94 of 114Anonymous functions • Inline statements or expressions • Used wherever a delegate type is expected • It can initialize a named delegete • It can be passed as the parameter where a named delegate type is expected • Two kinds of anonymous functions – Anonymous methods – Lambda expressions 95 of 114Evolution of delegates in C Named method Inline code (anonymous method) Lambda expression 96 of 114Anonymous method • No name, no overloading • Created using the delegate keyword • It is possible to add multiple statements inside its body 97 of 114Anonymous method (cont.) • Scope of the parameters is the anonymous method block • No jump from inside an anonymous method block to the outside, and vice versa. • Cannot access ref and out parameters of an outer scope • No unsafe code access inside its block • Not allowed on the left side of the operator is. 98 of 114Expression lambdas • Lambda expression with an expression on the right side of the operator = • Used dominantly in construction of expression trees • (input parameters) = expression • Parentheses optional if lambda has one param. • Input parameters separated by comma 99 of 114Expression lambdas examples • (x, y) = x == y The parameters types inferred by the compiler • (int x, string s) = s.Length x Specify types of the parameters when the compiler cannot inferre them from the code. • () = SomeMethod() Zero input parameters specified with empty parentheses. Note: a method call cannot be evaluated outside the .NET Framework (e.g. SQL Server) 100 of 114Statement lambdas • (input parameters) = statement; • Statements enclosed in braces • The body of a statement lambda can contain multiple statements (in practices, twothree) • Cannot be used to create expression trees 101 of 114Generic delegates – Func • System.FuncT,TResult T – argument type, TResult – return type (last type parameter) • Useful for encapsulating userdefined expressions that are applied to all elements of a data set A generic declaration of the delegate Func. Example of usage. 102 of 114Func delegate (cont.) • A lambda expression can be passed where ExpressionFunc type is required – System.Linq.Queryable Compiler can infere the Output: 5, 1, 3, 9, 7 type of the parameter n. Output: 5, 4, 1, 3 Output: 5, 4 103 of 114Type inference in lambdas • Compiler can infer the type of the parameters based on: – Lambda’s body – Parameter’s delegate type • Example: IEnumerableCustomer customers=... Standard query operator. 104 of 114Lambda expressions – general rules • The lambda must contain the same number of parameters as the delegate type • Each input parameter in the lambda must be implicitly convertible to its corresponding delegate parameter • The return value of the lambda (if any) must be implicitly convertible to the delegate’s return type 105 of 114Lambda expressions examples • Funcint,int f1 = x = x+1; • Funcint,int f2 = x = return x+1; • Funcint,int f3 = (int x) = x +1; • Funcint,int f4 = (int x) = return x+1; • Funcint,int f7 = delegate(int x) return x+1; • Invocation example: Console.Writeln(f1.Invoke(4)); 106 of 114Lambda expressions examples • Funcint,int,int f5= (x,y) = xy Invocation: Console.Writeln(f5.Invoke(2,2)); • Action f6 = () = Console.Writeline(); Function instance that does not receive any parameter nor returns value. Invocation: f6.Invoke(); • Funcint f8 = delegate return 1+1; Invocation: Console.Writeln(f8()); 107 of 114Language Integrated Query LINQ 108 of 114Content • Undestand what LINQ is • Learn what problems solves • See what its syntax looks like • Know where LINQ can be used 109 of 114What is LINQ • Language INtegrated Query • It is part of programming language syntax • Supported by: C, VB, Delphi Prism • Used for querying data • Supported the following types of data sources – Relational data – XML data – objects 110 of 114LINQ Architecture 111 of 114ADO .NET vs. LINQ ADO .NET LINQ • OO library for relational • SQLLike syntax that deals data access with pure objects • Mapping from relational to • Reduces the Impedance OO objects needed Missmatch • High Impedance Missmatch• Makes data querying more for mapping data from efficient storage to objects in an • One still must know the application format of the data 112LINQ Adapters • LINQ to Objects • LINQ to SQL • LINQ to XML • LINQ to Entities • It is possible to create own customized adapter – E.g. LINQ for Querying Twitter API 113 of 114References • ASP .NET MVC 5 Tutorial – Official 5/introduction/gettingstarted • Lambda expressions • LINQ Samples3fb9811b 114 of 114
Website URL