To display HTML content to the user, you can instruct the controller in the app to return a view.
A View
Provides the UI of the app to the user
Is used to display content of an app and also to accept user inputs
Uses model data to create this UI
Contains both HTML markup and code that runs on the Web server
57 trang |
Chia sẻ: thuychi16 | Lượt xem: 697 | Lượt tải: 0
Bạn đang xem trước 20 trang tài liệu Kĩ thuật lập trình - View, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
ViewNguyen Ha Giang1ObjectivesDefine and describe viewsExplain and describe the razor engineDefine and describe the HTML helper methods 2Working with ViewsTo display HTML content to the user, you can instruct the controller in the app to return a view.A ViewProvides the UI of the app to the userIs used to display content of an app and also to accept user inputsUses model data to create this UIContains both HTML markup and code that runs on the Web server3View EnginesAre part of the MVC Framework that convert the code of a view into HTML markup that a browser can understandAre divided in the following two categories:Web Form view engine: Is a legacy view engine for views that use the same syntax as ASP.NET Web Forms.Razor view engine: Is the default view engine starting from MVC 3. This view engine does not introduce a new programming language, but instead introduces new markup syntax to make transitions between HTML markups and programming code simpler4Specifying the View for an Action 1/8While creating an ASP.NET MVC app, you often need to specify a view that should render the output for a specify actionWhen you create a new project in VS.NET, the project by default contains a View directoryIn an app, if a controller action returns a view, your app should contain the following:A folder for the controller, with the same name as the controller without the Controller suffixA view file in the Home folder with the same name as the action5Specifying the View for an Action 2/8Following code shows an Index action that returns an ActionResult object through a call to the View() method of the Controller class:In this code, the Index action of the controller named HomeController that returns the result of a call to the View() method. The result of the View() method is an ActionResult object that renders a view6public class HomeController : Controller{ public ActionResult Index() { return View(); }}Specifying the View for an Action 3/8VS 2013 simplifies the process of creating a viewYou can create the view file by performing the following steps:Right-click inside the action method for which you need to create a view.Select Add View from the context menu that appears. The Add View dialog box is displayed, as shown in the following figure:7Specifying the View for an Action 4/8Click Add, VS automatically creates an appropriate directory structure and adds the view file to it.Following figure shows the view file that VS.NET creates for the Index action method of the HomeController class in the Solution Explorer window:8Specifying the View for an Action 5/8In the Index.cshtml file, you can add the following code that the view should display:This code creates a view with a title and a message as a heading9 My Test View Welcome to the Website Specifying the View for an Action 6/8When you access the Index action of the HomeController from a browser, the Index. cshtml view will be displayed.You can use the following URL to access the Index action of the HomeController:10http:///Home/Index the View for an Action 7/8You can also render a different view from an action method.To return a different view, you need to pass the name of the view as a parameter.Following code shows how to return a different view:This code will search for a view inside the /Views/Home folder, but render the AnotherPage view instead of rendering the Index view.11public class HomeController : Controller{ public ActionResult Index() { return View("AnotherPage"); }}Specifying the View for an Action 8/8While developing an ASP.NET MVC app, you might also need to render a view that is present in a different folder instead.To render such view, you need to specify the path to the view.This code will display the view, named Welcome.cshtml defined inside the /Views/Demo folder.12public class HomeController : Controller{ public ActionResult Index() { return View("~/Views/Demo/Welcome.cshtml"); }}Passing data 1/14In an ASP.NET MVC app, a controller typically performs the business logic of the app and needs to return the result to the user through a viewYou can use following objects to pass data between controller and view:ViewDataViewBagTempData13Passing data 2/14ViewDataPasses data from a controller to a viewThe life of a ViewData object exists only during the current requestThe value of ViewData becomes null if the request is redirectedViewData requires typecasting when you use complex data type to avoid error14ViewData[] = ;: Is a string value to identify the object present in ViewData: Is the object present in ViewData. This object may be a Stringor a different type, such as DataTimePassing data 3/14In this code a ViewData is created with two key-value pairs.The first key named Message contains the String value, Message from ViewData.The second key named CurrentTime contains the value, DataTime.Now15public class HomeController : Controller{ public ActionResult Index() { ViewData["Message"] = "Message from ViewData"; ViewData["CurrentTime"] = DateTime.Now; return View(); }}Passing data 4/14Following code shows retrieving the values present in ViewData:In this code, ViewData is used to display the values of the Message and CurrentTime keys16 My Test View @ViewData["Message"] @ViewData["CurrentTime"]Passing data 5/14ViewBag:Is a wrapper around ViewData.Exists only for the current request and become null if the request is redirected.Is a dynamic property based on the dynamic features introduced in C# 4.0Does not require typecasting when you use complex data type.17ViewBag. = ;: Is a string value that represents a property of ViewBag: Is the value of the property of ViewBagPassing data 6/14In this code a ViewBag is created with the following two properties:The first property named Message contains the String value, ‘Message from ViewBag’.The second property named CurrentTime contains the value, DataTime.Now18public class HomeController : Controller{ public ActionResult Index() { ViewBag.Message = "Message from ViewBag"; ViewBag.CurrentTime = DateTime.Now; return View(); }}Passing data 7/14In this code, ViewBag is used to display the values of Message and CurrentTime properties19 My Test View @ViewBag.Message @ViewBag.CurrentTimePassing data 8/14When you use a ViewBag to store a property and its value in an action, that property can be accessed by both ViewBag and ViewData in a viewIn this code, a ViewBag is created with property named CommonMessage20public class HomeController : Controller{ public ActionResult Index() { ViewBag.CommonMessage = "Common message accessible to both ViewBag and ViewData"; return View(); }}Passing data 9/14This code uses both ViewData and ViewBag to display the value of the CommonMessage property stored in ViewBag21 My Test View Accessed from ViewData:@ViewData["CommonMessage"] Accessed from ViewBag:@ViewBag.CommonMessage Passing data 10/14TempDataIs a Dictionary object derived from the TempDataDictionary classStores data as key-value pairs.Allows passing data from the current request to the subsequent request during request redirection.22TempData[] = ;: Is a string value to identify the object present in TempData: Is the object present in TempDataPassing data 11/14This code creates two actions. The Index action stores value to ViewData, ViewBag, and TempData. Then, redirects the request to the About action by calling the Redirect() method. The About Action returns the corresponding view, which is the About.cshtml view23public class HomeController : Controller { public ActionResult Index() { ViewData["MessageFromViewData"] = "ViewData Message"; ViewBag.MessageFromViewBag = "ViewBag Message"; TempData["MessageFromTempData"] = "TempData Message"; return Redirect("Home/About"); } public ActionResult About() { return View(); }}Passing data 12/1424 My Test View Message from ViewData: @ViewData["MessageFromViewData"] Message from ViewBag: @ViewBag.MessageFromViewBag Message from TempData: @TempData["MessageFromTempData"]Using Partial Views 1/5Represent a sub-view of a main view Allows you to reuse common markups across the different views of the app. To create a partial view in VS.NET, you need to perform the following steps:Right-click the Views/Shared folder in the Solution Explorer window and select Add->View. The Add View dialog box is displayed.In the Add View dialog box, specify a name for the partial view in the View Name text fieldSelect the Create as a partial view check box25Using Partial Views 2/5Following figure shows how to create a partial view in VS 2013.Click Add button to create the partial view26Check it to create a partial viewUsing Partial Views 3/5In the partial view, you can add the markup that you need to display in the main view, as shown in the following code: Content of partial view. The general syntax of partial view is as follows: @Html.Partial()Where,Partial_view_name: is the name of the partial view without the .cshtml file extension27Razor 1/2Is a syntax, based on the ASP.NET Framework that allows creating views.Is simple and easy to understand for users who are familiar with the C#.NET or VB.NET programming languagesFollowing code snippet shows a simple razor view containing both HTML markups for presentation and C# code28Razor 2/229@{var products = new string[] { "Vaio", "Dell", "Lenovo" };} Test View @foreach (var product in products) { The product is @product } @ syntaxRazor 3/4In the preceding code:A string[] is declared and initialized using Razor syntaxThen, Razor syntax is used to iterate through the elements of the array and display each element.The remaining code in the view is HTML code that displays the page title, body, and the array elements in a bullet list30Razor EngineThe MVC Framework uses a view engine to convert the code of a view into HTML markup that a browser can understand.Razor engine:Is used as the default view engine by the MVC FrameworkCompiles a view of your app when the view is requested for the first time.Delivers the compiled view for subsequent request until you make changes to the viewSupport Test Driven Development (TDD) which allows you to independently test the views of an app31Razor Syntax Rules 1/5A RazorFirst requires identifying the server-side code from the markup code to interpret the server-side code embedded inside a view fileUses the @ symbol, to separate the server-side code from the markup code.32Razor Syntax Rules 2/5While creating a Razor view, you should consider following rules:Enclose code blocks between @{ and }Start inline expression with @Variables are declared with the var keyworkEnclose strings in quotation marksEnd a Razor code statement with semicolon;Use the .cshtml extension to store a Razor view file that uses C# as the programming languageUse the .vbhtml extension to store Razor view file that uses VB.NET as the programming language33Razor Syntax Rules 3/5Razor support code blocks within a view. A code block is a part of a view that only contains code written in C# or VBThe general syntax of using Razor is as follows: @{ }Where,Code: is the C# or VB code that will execute on the serverFollowing code snippet shows two-statement code blocks in a Razor view @{ var myMessage = "Hello World";} @{ var num = 10;}34Razor Syntax Rules 4/5Razor also support multi-statement code blocks where each code block can have multiple statements.Multi-statement code block allows you to ignore the user of the @ symbol in every line of codeFollowing code snippet shows a multi-statement code block in a Razor view: @{ var myMessage = "Hello World"; var num = 10; }This code shows a multi-statement code block that declares the variables, myMessage and num35Razor Syntax Rules 5/5Similar to code block, Razor uses the @ character for an inline expression.Following code snippet shows using inline expressions:This code uses two inline expression that evaluates the myMessage and num variables.When the Razor engine encounters the @ character, it interpreted and immediately following variable name as server-side code and ignores the following text36@{var myMessage = "Hello World";var num = 10;}@myMessage is numbered @numRazor Syntax Rules 6/6 The email ID is: nh.giang@@hutech.edu.vn In this code, Razor:Interprets the first @ symbol as an escape sequence character.Uses an implicit code expression to identify the part of a server-side codeSometimes, Razor may also interpet an expression as markup instead of running as server-side code.37VariablesAre used to store data.In Razor, you declare and use a variable in the same way as you do in C# programFollowing code snippet shows declaring variable using Razor38Loops 1/2While developing an ASP.NET MVC Web App, you might require executing same statement continuallyIn such scenario you can use loops.C# support the following four types of loop constructs:The while loopThe for loopThe dowhile loopThe foreach loop39Loops 2/2Following code snippet shows the Razor code that uses a while loop: 40Conditional Statements 1/2Allows you to display dynamic content based on some specific conditions.Includes the if statement that returns true or false, based on the specified condition.41Conditional Statements 2/2Following code snippet shows using the switch statement using Razor: 42Arrays 43HTML Helper Methods 1/13In ASP.NET MVC Framework, helper methods:Are extension methods to the HtmlHelper class, can be called only from views.Simplifies the process of creating a viewAllows generating HTML markup that you can reuse across the Web app.Some of the commonly used helper methods while developing an MVC app are as follows:Html.ActionLink(), Html.BeginForm(), Html.EndForm()Html.Label(), Html.TextBox(), Html.TextArea()Html.Password(), Html.CheckBox()44HTML Helper Methods 2/13Html.ActionLink() helper method allows you to generate a hyperlink that points to an action method of a controller class @Html.ActionLink(,,)Link_text: is the text to be displayed as a hyperlinkAction_method: is the name of the action method that acts as the target for the hyperlinkoptional_controller: is the name of the controller that contains the action method that will get called by the link.45HTML Helper Methods 3/13Following code snippet shows using a Html.ActionLink() helper method46HTML Helper Methods 4/13Html.BeginForm() helper method:Allows you to mark the start of a formCoordinates with the routing engine to generate a URLIs responsible for producing the opening tag.@{Html.BeginForm(, )}Action_method: is the name of the action methodController_name: is the name of the controller class.Once you use the Html.BeginForm() helper method to start a form, you need to end a form using the Html.EndForm() helper method 47HTML Helper Methods 5/13Following code snippet shows using the Html.BeginForm() and Html.EndForm() helper methods:In this code the Html.BeginForm() method specifies the Browse action of the Home controller as the target action method to which the form data will be submitted. 48HTML Helper Methods 6/13Html.Label() helper method:Allows you to display a label in a formEnables attaching information to other input elements, such as text inputs, and increase the accessibility of your app @Html.Label() where, label_text: Is the name of the label 49HTML Helper Methods 7/13Html.TextBox() helper method:Allows you to display an input tagUsed to accept input from a user @Html.TextBox(“textbox_text")where,textbox_text: is the name of the text box50HTML Helper Methods 8/13Html.Textarea() helper method:Allows you to display a element for multi-line text entryEnables you to specify the number of columns and rows to be displayed in order to control the size of the text area 51HTML Helper Methods 9/13You can use Html.Password() helper method to display a password field.52HTML Helper Methods 10/13You can use the Html.CheckBox()helper method to display a check box that enables the user to select a true or false condition53HTML Helper Methods 11/13Html.DropDownList()helper method:Return a element that shows a list of possible options and also the current value for a field.Allows selection of a single item. @Html.DropDownList("myList", new SelectList(new[] {,,}), “Choose")where,Value1, value2, and value3 are the options available in the drop-down list.Choose: is the value at the top of the list54HTML Helper Methods 12/13The Html.RadioButton() helper method allows you to provide a range of possible options for a single value @Html.RadioButton("name", "value", isChecked)Where,name: is the name of the radio button input elementvalue: is the value associated with a particular radio button optionisChecked: is a boolean value that indicates whether the radio button option is selected or not55HTML Helper Methods 13/13The Url.Action() helper method generates a URL that targets a specified action method of a controllerUrl.Action(, )Where,Action_name: is the name of the action methodController_name: is the name of the controller class56SummaryThe views are used to display both static and dynamic contentView engines are part of the MVC Framework that converts the code of a view into HTML markup that a browser can understandYou can use ViewData, ViewBag, and TempData to pass data from a controller to a viewA partial view represents a sub-view of a main view.Razor is syntax, based on ASP.NET Framework that allows you to create viewsThe MVC Framework uses a view engine to convert the code of a view into HTML markup that a browser can understandThe MVC Framework provides built-in HTML helper methods that you can use to generate HTML markup and you can reuse it across the Web app.57