1 / 47

Introduction to the MVC Pattern: Building Complex Applications with MVC

Learn about the Model-View-Controller (MVC) architectural design pattern for building interactive applications. Discover the benefits and responsibilities of each component and understand how MVC is implemented in web development using ASP.NET MVC.

Download Presentation

Introduction to the MVC Pattern: Building Complex Applications with MVC

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Social Media AndGlobal Computing Introduction toThe MVC Pattern

  2. What is MVC? • MVC is a approach to building complex applications that breaks the design up into three components: The Model, the View and the Controller:

  3. The MVCPattern • Model-View-Controller ("MVC") an architectural design pattern for interactive applications dividing tasks into three separate modules: • one for the application model with its data representation and business logic, • the second for views that provide data presentation and user input, and • the third for a controller to dispatch requests and control flow.

  4. The MVCPattern • In the MVC Design Pattern: • The view manages the graphical and/or textual output to the portion of the interaction with the user. • The controller interprets the inputs from the user, commanding the model and/or the view to change as appropriate. • The model manages the behavior of the data and the state of the application domain.

  5. The MVCPattern • Most Web-tier application frameworks use some variation of the MVC design pattern • The MVC (architectual) design pattern provides a host of design benefits

  6. Benefits of MVC • Clarity of design • easier to implement and maintain • Modularity • changes to one don't affect the others • can develop in parallel once you have the interfaces • Supports Multiple domains • Web, desktops, games, spreadsheets, Powerpoint, IDEs, UML reverse engineering, ….

  7. Model • The Model's responsibilities • Provide access to the state of the system • Provide access to the system's functionality • Can notify the view(s) that its state has changed

  8. View • The view's responsibilities • Display the state of the model to the user • At some point, the model (a.k.a. the observable) must registers the views (a.k.a. observers) so the model can notify the observers that its state has changed

  9. Controller • The controller's responsibilities • Accept user input • Button clicks, key presses, mouse movements, slider bar changes • Send information to the model • Send appropriate information to the view

  10. MVC in a Web Interaction

  11. ASP.NET MVC • Microsoft's newest Web development frameworkimplementation • Easy to implement design principles and patterns • Integral part of ASP.NET • Alternative to Web Forms Applications • First implementation by Scott Guthrie • Built using core ASP.NET features

  12. The ASP.NET MVC Framework presents a different paradigm than the ASP.NET Web Forms Framework: • Instead of focusing on writing code for individual controls (which you need to do with Web Forms), you focus on writing code for Views or Models. • Typically AJAX and/or jQuery are used to handled the User Interaction with individual controls ASP.NET MVC

  13. Web Forms vs. MVC Extensibility • ASP.NET has a provider model • Membership model example • MVC has powerful pluggable model • The Default view engine can be implemented in one of the following three ways: • Use the default component • Extend the default component • Replace the default component

  14. The Tenets of MVC • Separations of concerns • Convention over configuration • Keep it DRY: Don't Repeat Yourself • Be helpful, but get out of my way

  15. Web Forms vs. MVC Blending of Concerns • Web forms is almost a hybrid • Forces a mixture of view and controller design approaches example • False sense of separation from code behind file • Reality: close coupling • MVC's Separation of Concerns • Encourages good coding practices • Ideally suited to Web application development • Natural for HTTP Requests and Responses

  16. Web Forms vs. MVC Control over HTML • Web forms server controls provide rich functionality, but … • Produces unreadable, monolithic blocks of HTML • MVC gives you complete control over HTML • Produce clean HTML easy to control with CSS • Produce clean HTML easy to control with AJAX and JQuery

  17. Web Forms vs. MVC Open Source • MVC Source Code isavailable • Liberal open source license: Microsoft Public License

  18. Web Forms vs. MVC Serves Methods, Not Files • ASP.NET Web Forms File Request: • http://www.example.com/index.aspx?ID=5 • Loads index.aspx file and get ID = 5 as parameter in ViewState • MVC Method Request: • http://www.example.com/Home/Details/5 • Maps to ‘Home’ controller • And ‘Details’ action method • With Item ID of 5

  19. Conventions Over Configurations • MVC Conventions reduce the number of configuration files • Key Folders use Naming Conventions • Controllers folder • Name must be SomeNameController.cs • [SomeName] is the Controller name • [SomeName] comes after the domain in the URL MVC Project Conventions

  20. More MVC Folder Conventions • Views folder • Contains subfolders with Controller names • A Controller’s Views are in its subfolder • Any views shared by 2 or more controllers should go in the Shared folder • Ex: Error page and Master Template page • Models folder • Contains Models files for custom data objects and classes and shared references for your applications • Datastores/Databases should be places in the App_Datafolder MVC Project Conventions

  21. MVC Views • No Code-Behind or Page events • The interaction with the application is through a Controller • Controller passes data to the view in the form of a String or a Model Object • Views are created using Controller action methods • Views can also be created using the Solution Explorer MVC Project Views

  22. MVC Master Pages • Master pages allow you to create views with predefined elements • You can have multiple master pages in an application MVC View Templates

  23. Each view is associated with an MVC Controller Method • public ActionResultMethodName() • { return View(); } MVC Controller Action Methods

  24. In MVC you cannot run a View that has no corresponding Action Method. Action Methods are behind every View • You need to create the Action Method for the View before you create the View • Once you have created the action method, to create the View, you right-click on the Method and select “Add View” MVC Views and Action Methods

  25. MVC Views can be associated With Multiple Methods • An Action Method that is the result of a Form Submission has special HTTP attributes identified before it and can redirect the user to another view: • [HttpPost] • public ActionResultMethodName(String id, FormCollection collection) • { Session["Name"] = collection[0]; Session["Email"] = collection[1]; Session["Phone"] = collection[2]; return RedirectToAction("NextView");}

  26. When you create a View, you can always associate it with a View Template • Once you have created the action method and you choose the “Add View,” you can select a Master page from the Shared folder to act as the View template for that view. • Master pages allow you to create views with predefined elements • You can have multiple master pages in an application MVC Views and View Templates

  27. Passing data to a View through ViewBag object and Inline Code • ViewBag is a property of the ViewPage class • It allows you to create field names that you can then assign object value to: • ViewBag.Message = "Hello There!" • Once set in a Controller action method, it can be used in a View with Inline Code (called Razor syntax) such as the following: • <h2> @Html.Raw(ViewBag.Message) </h2> MVC ViewBag Data

  28. MVC Action Methods Can Pass Data to other Action Methods Through Session Fields • Action Methods can pass data to other Methods using Session Field Variables: • public ActionResultMethodName() • { Session["Name"] = "John Smith"; Session["Email"] = "JohnSmith@gmail.com"; Session["Phone"] = "555-123-4567"; return View();}

  29. Formatting data in a View With the HTMLHelper Class • There are many HTMLHelper methods from the HTML Helper class: • http://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper.aspx • The following formats an link with the text “Click here” and sends it to the “Brochure” view of the “Home” controller: • @Html.ActionLink("Click here","Brochure","Home")

  30. MVC Helper Methods • The BeginForm() method is used to create a Form for submitting fields: • @{ using (Html.BeginForm()) { • … • } }

  31. MVC Helper Methods • This method is used to create a Label using the HTML label tag: • @Html.Label("Text For Label")

  32. MVC Helper Methods • This method is used to create a single line Text box: • @Html.TextBox("FieldName")

  33. MVC Helper Methods With Default Values • This method is used to create a single line Text box with a default value: • @Html.TextBox("FieldName","Default")

  34. MVC Helper Methods • This method is used to create a multi line Text box: • @Html.TextArea("FieldName")

  35. MVC Helper Methods With Default Values • This method is used to create a multi line Text box with a default value: • @Html.TextArea("FieldName","Default")

  36. MVC Helper Methods • This method is used to create a checkbox: • @Html.CheckBox("FieldName")

  37. MVC Helper Methods With Default Values • This method is used to create a checkbox that is either checked or unchecked if the default value is True or False respectively: • @Html.CheckBox("FieldName",true/false)

  38. MVC Helper Methods • This method is used to create a radio button: • @Html.RadioButton("FieldName","FieldValue")

  39. MVC Helper Methods With Default Values • This method is used to create a radio button that is either selected or unselected if the default value is True or False respectively: • @Html.RadioButton("FieldName","FieldValue",true/false)

  40. MVC Helper Methods • This method is used to create (action) links on a page. The following formats an link with the text “Click here” and sends it to the “Brochure” view of the “Home” controller: • @Html.ActionLink("Click here","Brochure","Home")

  41. MVC Helper Methods • If you omit the controller argument, then the link will keep you in the same controller that you were in when you clicked on the link: • @Html.ActionLink("Click here","Brochure")

  42. MVC Helper Methods • You can use the Action Link to send arguments to the Controller function. The following sends the ID argument with a value to the Brochure function: • @Html.ActionLink("Click here","Brochure","Home", • new {id = value}, null)

  43. The following creates a Form: • @{ using (Html.BeginForm()) { • @Html.Label("Text Box"): • @Html.TextArea("Field1", "First default") • <p></p> • @Html.Label("Text Area"): • @Html.TextArea("Field2", “Second default") • <p></p> • Check box 1: @Html.CheckBox("CheckBox1", false) <br /> • Check box 2: @Html.CheckBox("CheckBox2", false) <br /> • <p></p> • @Html.Label("Radio button 1"): • @Html.RadioButton("Field5", "RadButton1", false) <br /> • @Html.Label("Radio button 2"): • @Html.RadioButton("Field6", "RadButton2", false) <br /> • <p></p> • <input type="submit" value="Save Answers" /> • } } Example

  44. Example • The Form created:

  45. The DropDownList HTML Helper Method • You can add a DropDownList to your HTML page by using the Html Helper function called DropDownList. It gets a name of a ViewDataSelectList field, and an optional first item in the list: • @Html.DropDownList("ListItems", "--Select One--")

  46. The DropDownList HTML Helper Method • For the previous example, some code would be needed in the Controller function to set the ViewDataSelectListfield: • String[] options = {"1st Option", "2nd Option", "3rd Option"}; • ViewData.ListItems = new SelectList(options, "SelectedItem");

  47. The DropDownList HTML Helper Function • The previous Controller function and HTML Helper function would produce the following:

More Related