Download presentation
Presentation is loading. Please wait.
1
View In MVC Mo Rezai
2
Aims and Objectives In this lecture, we will
Investigate the MVC request-processing cycle Look at how we create Views Look at the URL Routing module
3
Remember Request-Processing cycle
View Data Storage Controller Business Tier Presentation Model Integration Access Controller receives request and delegates processing of the request to the model. Model, to do what it does, presumably requires access to data. Model makes request for the data to the Data Access objects in the integration layer. Data Access object processes the request for the data and returns the data back to the model. Model does the processing and returns result to the controller. Controller delegates the rendering to a View and also passes model-generated data to the view. View renders response using model-generated data. View is a push model – View does not ask for data – Data is pushed onto the view.
4
View Views are public face of the MVC applications
A view is directly associated with a controller action Synonym to web forms in Asp.Net Websites With Asp.net Mvc applications , we have; .ASPX Views – Not quite like Asp.Net .ASPXs Razor Views No Web Controls HTML and HTML Helpers Public face of the MVC application is a set of views. So views are responsible for rendering HTML pages that people see when they visit Websites. Remember that a controller action is responsible to receive a request from a person and work with a model to prepare data and then pass that date to a view for rendering. There is therefore strong association between a view and a controller action. Of course controller actions do not always return views but most of the times they do. On the other hand a view is invoked only by a controller action. Views do for Mvc applications what .aspx does for Asp.net Websites. In fact with MVc applications we still have views of type .aspx. These are not quite like the old aspx pages in that there is no code behind with the views. It makes sense not to have it because with Mvc we can not have business logic or data access in views. So it makes sense to remove those from these. With old asp.net aspx we would get Web controls within the toolbox. Now, web controls were not only to do with presentation but also to do with business logic. For example you could associate events with those and usually events were about logic as a result of a user action, for example a buttin_click or a calendar_selected. For this reason, views do not get to use web controls. There are no web controls to use at the moment although that does not necessarily mean people are not working on creating them for mvc web controls. Currently though we do not have them available. In place of those we have HTML and HTML helpers. HTML helpers are server-side actions to help us develop pages. Html helpers generate text. For example Html.beginform helper generates the requires tags and bits and pieces to start off a form.
5
Creating Views In Controller;
Right-click within a controller action and ‘Add View’ Various options include using Master Page, Strongly-Types View Add HTML to view Add Scripts to a view We can write our own views if we want to but a much easier way of creating a view is to use the tool to generate the code for the view. Working on a controller if we right-click within a controller action and add a view, the wizard would help us generate the code for the view. In creating a view we could use a master page in which case automatically ContentPlaceHolders are placed in the view. We could create strongly-typed views that take advantage of data that is already configured by a model data. You can add any html extras. For example you can add an image, flash, Silverlight or even java applets in a view. You can also add scripts to a view. To add script you use a <% %> script delimiters.
6
Presenting Controller-Generated Data
Data is prepared by controller Controller populates a bag variable with data ViewData Request View Controller Data needs to be delivered from the controller to the view. The delivery mechanism is through using something called ViewData. So we take advantage of ViewData to pass information from controller to view. You can use ViewData to represent any type of information including strings, objects or even Database records. You already know about container of data or better still database records – DataSet – so perhaps you can reflect on what the ViewData is using behind the scene to do what it does. ViewData is a property of controller and it is implemented as a data dictionary. For example imagine you want to pass a set of database records from a controller action to a view; Within the Controller you add an item to ViewData – You do this by adding the item to the ViewData dictionary that is exposed by the controller’s ViewData property. You add the item to the dictionary as key-value pair. ViewData is implemented as a dictionary Contains key-value pairs
7
Using ViewData Example
Key value pair examples are like key: Message pairs with Value:”Welcome to ASP.Net ..”
8
Determining ViewData Data Type
Any type of object can be passed by ViewData Each View is derived from System.Web.Mvc.ViewPage ViewPage provides a number of facilities, example: ViewData property ViewData property returns a ViewDataDictionary object Any type of object can be passed by ViewData. MVC view inherits from viewpage object that is in System.web.Mvc namespace and so it gets quite a bit from that. For example it gets certain properties such as the controller action name property and Viewdata property. Here we have a Create() action and the idea is to use a dropdownlist that is populated from the database for the category. ViewData property returns a ViewDataDictionary object. In this example we have added a list of Categories to the Data dictionary – The list is identified in this case by Category_id. We have created the identifier programmatically. Within the view then from the dictionary we can access the list and pass the list to the HTML Helper using the identifier.
9
Strongly-Typed Views Preferred method of passing data to View
Derived from System.Web.Mvc.ViewPage(Type) Data is passed from controller to view via View() method If you don’t want to clutter your views by casting the ViewData, you can create strongly-typed views. With MVC strongly-typed views are preferred. This is because we do not have to worry about the identifiers. In this example ViewData is of type List (of music_categories).
10
ViewData.Model property
ViewDataDictionary has a property called ‘Model’ Within controller action, assign anything to the ‘ViewData.Model’ OR Cast ‘ViewData.Model’ property automatically in a view There are a number of ways to work with the viewdata.model. For example we have already seen examples of passing the model to the view: <HttpGet()> Function EditRecording(ByVal id As Integer) As ActionResult Dim _recording As music_recordings = _MusicSerachService.GetMusicRecording(id) Return View("EditRecording", _recording) End Function This is also setting the Model property of ViewData and it is doing it implicitly - We do not see it in the code.
11
HTML Helpers Provided to generate many of the standard HTML elements
Derived from System.Web.Mvc.HtmlHelper class Generate attribute values relevant to MVC Return strings that are HTML content Help build views with far less work Less complex but synonym to Web Control in Web Forms Example: HTML ActionLink() HTML Helpers are used to render html content such as HTML forms, HTML URLS, HTML You can build an entire MVC website without using HTML helpers but using them makes your life a lot easier. HTML Helpers to Views are like what web controls were to web forms. Helpers are a lot more light weight as they do not have event handling. An example of HTML helper is HTML.actionlink(). This is the easiest way to generate HTML link in a view. Now there is of course a difference between the ordinary a URL and an link that you generate using HTML.actionlink() in that in this case the link will not point to a view and it points to a controller action. HTML.actionlink() has several parameters. In the example we have ‘linkText’, ‘actionName’, ‘controllerName’, ‘htmlAttributes’, ‘protocol’, etc. HTMLAttributes could be used to style the link for example its colour, its font, etc. Protocol is the protocol for the link. For example default is http but protocol could be https. Generates: <a href=“ /MusicAdmin/Edit/1”>Edit</a>
12
HTML Helper examples There are also ViewHelpers
Rendering HTML Form elements: Html.BeginForm() Html.CheckBox() Html.ListBox() Html.RadioButton() Html.TextBox() Html.Password() See There are also ViewHelpers Rendering Image Links: URL.Action() helper Actionlink can not be directly used to render an image link. This is because HTML.actionlink() encodes its link automatically and so you can not pass an image tag to this and expect it to render as an image. For rendering an image you use URL.Action() helper. There are various HTML helpers to help you build a form. What used to be web control is now html helper. This list does not intend to be exhaustive. There are lots more including validation helpers, etc. Each helper has its own list of parameters and so the thing becomes quite a lot to remember. This is one of those things you have to have a good reference and just use the reference whenever you need to.
13
Custom HTML Helpers Equivalent to ASP.Net Web Form Controls
Helpers are lightweight Web controls are heavyweight with event handling MVC comes with limited number of HTML Helpers You can create you own custom HTML Helpers Create extension method on HtmlHelper class In the MVC world Helpers are basically equivalent to web controls. So if you have Html.textbox helper, you expect to have textbox web control. The difference is that with textbox web control you could do things, for example build event handling with business logic in it. Web controls were heavyweight whereas HTML Helpers are light weight with no business logic or event handling. They are purely for presentation - HTML.Textbox() paints a textbox and that is it. ASP.Net people Have created certain number of helpers that they thought were to be the most commonly used. The list of helpers is not exhaustive and you might come across situations where you would need to build your own. Creating your own helpers is relatively easy.
14
Validating Form Data Represent validation errors with something called Model State Dictionary Both the controller class and the view class have ModelState property ModelState exposes Model State Dictionary Properties of the ObjectToCreate are validated ModelState.IsValid property returns False if validation fails Action redisplays form for ObjectToCreate with error message(s) This is about validating the data that is inputted into a form. There is something called model state dictionary which is a special types of dictionary. Special in that it is only used for storing validation errors. The idea is that the validation errors are passed from the controller to the view using this dictionary that both controller and the view have access to. Both controller and the view have a property called the ModelState. This property exposes the model state dictionary. If you are adding a record to the database, you have an object to create and this object would have a number of properties that are mapped to the entry fields in the form. In case entries cause validation failure, ModelState has a property called IsValid that returns false and action has to then redisplay the form with the appropriate errors. If ModelState.IsValid property returns true, ObjectToCreate is added to the database.
15
Validating Form Data Example
Here our ObjectToCreate is recording. With the help of AddModelError of ModeState we are adding to the model state dictionary a validation message associated with a key. The key usually corresponds to the property being validated. We are testing to see if thee is an input for the title property of the object.
16
URL Routing Consider ugly URL: URL structure may have shortcomings:
Changes to application structure impacts on URL Affects search engine optimisation – high weighting to keywords used in URL Leaks implementation technology – May compromise security We have all seen URLs such as this one. Let us say these are not clean URLs. Let us say they are ugly URLs. They are not ideal for a number of reasons. The idea is that the URL must be independent of the application structure. URL should be decoupled from application structure. You might change your implementation and that may well affect the structure, for example you might want to create or get rid of directories and move things about. What you do not want to happen is that the URLs that have been recorded for the resource, say through bookmarks, fail. More importantly, we know that the search engine optimisation gives keywords in URLs high weighting – they are important. Changes to the structure would then be likely to cost us quite heavily. Sometimes looking at a URL, you can tell what technology they have used to implement. For example there might be references to .php or .jsp. Now if someone is intent to attack the site, this would give them a few clues that might be quite helpful to them.
17
Routing systems Aim to provide logical URLs
Decouple URL from application structure and logic Add flexibility to the system Possible to change application’s URL without affecting the implementation Possible to change application structure without worrying about the URLs So what we have are URL routing systems and we have these systems in many of the frameworks and implementation platforms. The idea is to go away from physical URLs where URL reflects the physical structure of the application and move towards more logical structures. And this will give us flexibility in that we now can change the application structure totally independently from the URLs and we may even want to change the URL structure without worrying how it is going to affect the implementation. We would like to be decoupling the URL structure from the application structure.
18
URL Routing MVC Framework comes with default URL routing rules
Default routing maps Leading URL Path to a class whose name starts with the URL path “../Customers/” is mapped to “CustomersController“ Controller Class i.e. “.../Customers/”, “.../Customers/Add” and “.../Customers/Delete/Customerid”are all mapped to CustomersController Controller Class There is a default/preconfigured rule for routing of the URLs to the controller classes. This is so that as developers we can just get on with the job as oppose to mess around with these configurations – The framework is trying to do as much as possible for us. The default convention is defined in the Global.asax file of your application. This is of course by concention – if you are not happy with the url mapping, then this could be altered by changing the settings in Globab.asax. It basically picks up a path in the URL and maps it to one controller whose name starts with that path in the URL. For example you might have If there is a controller class called CustomersController, this URL is mapped to this controller. So Controllers are basically responsible for responding to requests mage against the Website.
19
Asp.Net Mvc Routing System
Provides two areas of functionality: Inbound Routing - Maps incoming URLs to controller/action Outbound Routing (or Link Generation) – Generates outgoing URLs that can be used to call back to controller/action There are two aspects to routing; One is that inbound routing – that is the rule for the URLs that clients invoke for services. The other bit of this are the URLs that you embed in views that application renders to the client.
20
Request Processing using Routing Table
2 1 Controller Model 6 3 7 4 Request comes in through clicking a URL. Routing table is consulted – Inbound routing – URL is matched against routing rules to determine the controller and the action. This is simply pattern matching to get a match. The appropriate controller and the action are invoked. Controlled delegates the work to a model. Model returns data to the controller. Controller delegates rendering to a view. 6&7 in fact. View in return consults the routing table – Outbound routing (Link generation) - Routing rules are used to generate the appropriate URLs for links on the page, in this case for example title of recordings or Create New link. 8. URLs for links are generated to conform to the rules and page is rendered. 5 View Response 8
21
The Default Route Table
Global.asax contains event handlers for application lifecycle events Create Routing Rules within the application_start() event – A collection of Route objects is created Each Route object has properties: Route name URL Structure with possible parameters Optional defaults for parameters Route constraints – Example HTTP Method Each application has one special file in the route directory of the application called Global.asax. For example it has an application_start event. Anything you put inside that event it gets executed every time application is started. This special file is used for application wide initialization and any activities that are application wide. For example if you want to have a count of visitors’ count you can do that within this file. All you have to do is to have an application variable set in the application_start event and increment that every time you have a new session. You can log application level details with the help from different events. So these are variables and global settings that are to do with application events and session events. It can have events such as application_start(), application_end(), session_start(), session_end(), etc. We create our routing rules within the application_start() event, in other words we create them every time application starts. So we get a collection of objects we call route objects. A route object would have a number of properties such as Route name, URL structure, we may have defaults for parameters, there maybe constraints for example we may want the routing rule to be only available is accessed using HTTPGet, we may want the routing rule only used for this particular IP address, etc.
22
Default Route example Route Name Default URL Parameters Parameters
Default route looks like this. Exercise: Write these on the board and ask if they satisfy the rule and what the controller, action, id are. All the examples are in-coming URLs and they all satisfy. URL: ../Home Controller:Home, Action:Index, id=“” URL: ../Music/Recordings/Jazz Controller:Music, Action:Recordings, id=Jazz URL: ../Video/Categories/10/20/30 Controller:Video, Action:Categories, id=10
23
Defining New Routing Rule
New Routes can be added to the Route Table For Parameters, defaults can be provided UrlParameter.Optional for optional parameters For incoming requests, Routes are evaluated in the order they are registered Request is dispatched to first Route that is satisfied No Best-fit algorithm here We can add new routing rules to the table and very much like the default rule we can have defaults for parameters and have optional parameters. Essentially what this means therefore is that we can have a number of rules and the question is which rule is to kick in. The answer is that the order in which they appear in the table is important because the 1st satisfied rule is the one that kicks in. We are not going to look for the best fit but we are going to be satisfied with the 1st one that does the job. So the idea is that the defaults should never be at the top because default basically facilitates all.
24
Reference Walther, S, "ASP.NET MVC Framework", SAMS
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.