day7
Post on 24-Jun-2015
180 Views
Preview:
TRANSCRIPT
CSE 136 - Lecture 7
Presentation Overview MVC (Model, View, Controller) ASP.NET MVC 3.0
Routing in detail Controller in detail View in detail
Introduction
PresentationLayer
MVC
ModelDTO
Same Model?
Not alwaysgood
4111-1111-1111-7361
xxxx-xxxx-xxxx-7361
Presentation Layer
It’s what users see Handling complicated page flows Two components of the presentation
layer User Interface - What you see &
interacting with Presentation Model/Logic - Data flow
between the business logic and presentation layer
Presentation model vs Business model
What are the objects in the GUI gannt-chart
class schedule{ string name;
DateTime start;DateTime end;
int x, y, bar_length; int CalculatePoints() { … } // etc...}
List<schedule> project = new List<schedule>();
GUI specific
GUI can startdeveloping
without BLL data
Data objects from BL layer may be different
class schedule{
DateTime start;DateTime end;
string name; }
DTO on both PLand BLL to transferdata between them
MVC - Model View Controller
Create three distinct objects Model, View, and Controller
HTMLprocess user's
request
Serviceclient
MVC
MVC in desktop application environment.
update address event [update] buttonevent handler.Verify user input
actual update tothe object anddatabase
update completed
reload data from model
MVC - Pro and Con
Pro Decoupling – GUI/CSS developers do their
job, C# developers code the Controller, model and tests
You can test the logical flow by a test program to talk to the Controller directly
Con View has intimate knowledge of the Model
(when page refresh)
ASP.NET
Uses .NET Framework Compiled Multi-language (C#, VB, C++, etc) Host under CLR Code execution (i.e. Garbage collection) Object-oriented AJAX development
ASP.NET - Page Class Functions
Request - Handle request from user Request.QueryString.Get("pid"); Request.Form.Get("first_name"); HttpCookie myCookie = Request.Cookies["user_id"];
Response - Handle response to user Response.Redirect("newpage.aspx"); Response.Cookies.Add(myHttpCookie);
Server - URL encode/decode Server.URLEncode(url1);
Application - Application variables (name/value pair) Application["imageDir"] = "image.myserver.com"; <img src="<%= Application["imageDir"]%>/images/1.gif">
Session - Storage per user. It Expires/times out Session["first_name"] = "John";
ASP.NET MVC
Powerful Routing System Good for search engine Friendly URL (copy & paste)
Builds on ASP.NET platform object oriented multiple languages
Easy to develop (debugging) Easy to deploy (going live, updates)
MVC Architecture 1
Requesthttp
controller Model DatabaseStorage
modelViewhtmlResponse
MVC Architecture 2
controller ModelRequest
http
DTO
BL ServiceDomainModel
DAL
ViewmodelResponse html
DifferentModels
Some companiesUse the same model
MVC Web - Directories
Directory Purpose
/Controllers Where you put Controller classes that handle URL requests
/Models Where you put classes that represent and manipulate data
/Views Where you put UI template files that are responsible for rendering output
/Scripts Where you put JavaScript library files and scripts (.js)
/Content Where you put CSS and image files, and other non-dynamic/non-JavaScript content
/App_Data Where you store data files you want to read/write.
Expand the /Views directory
/Home/Account/Shared
Several template files within them were added by default
homepage
custom directory
common to all
Site master files(header, footer, leftnav, etc)
MVC Web - Routing
Open the file / Global.asax.cs
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); }
optional route name
any controller you create
any method in the controller
default value
MVC Web - Routing example
routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } );
(Default value)
The following URLs will match the above routing definition
URL
/
/Students/
/Students/Details/1
/Students/Edit/1
/Books/
/Books/List
{controller = "Home", action="Index", id=""}
{controller = "Students", action="Index", id=""}
{controller = "Students", action="Details", id="1"}
{controller = "Students", action="Edit", id="1"}
{controller = "Books", action="Index", id=""}
{controller = "Books", action="List", id=""}
Later, you may add more routing to parse: / DailySpecial/7-1-2011
routes.MapRoute( "Specials", "DailySpecial/{date}", new { controller = "Special", action = "" } );
MVC Web - Routing orderParse the URL: / DailySpecial/July_1
routes.MapRoute( "Specials", "DailySpecial/{date}", new { controller = "Special", action = "" } );
routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } );
{controller="DailySpecial", action="7-1-2011
If you reversed the MapRoute order and parse / DailySpecial/July_1
routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } );
routes.MapRoute( "Specials", "DailySpecial/{date}", new { controller = "Special", action = "" } );
This will never be reached
MVC Web - more Routing
Receiving Parameter Values in Action Methods
http://www.mysite.com/Catalog/Red
routes.MapRoute(null, "Catalog/{color}",new { controller = "Products", action = "List" }
);
In the ProductsController file:
public ActionResult List(string color){
// Get a list of products with given color
}
http://www.mysite.com/Catalog No paramspecified
routes.MapRoute(null, "Catalog/{color}",new { controller = "Products", action = "List", color =
UrlParameter.Optional });
MVC Web - Generate URL
Generating Outgoing URLs
@Html.ActionLink("See all books", "List", "Books")
Action/method Controllerbecomes
<a href="/Books/List">See all books</a>
@Html.ActionLink("CSE Books", "List", "Books", new {subject="CSE", page=1 }, null)
Generating Outgoing URLs (with parameters)
becomes
<a href="/Books/List?subject= CSE&page=1">CSE Books</a>
MVC Web - controller 1
Controller
Receiving user input
moving the user around between different UI views
A bridge between the Web and your presentation model
Controller Background:
All Controllers Implement IController
MVC Framework comes with a standard base class for controllersSystem.Web.Mvc.Controller which implements IController on your behalf
[OutputCache(Duration=600, VaryByParam="*")]public class DemoController : Controller{
public ViewResult ShowGreeting(){
ViewData["Greeting"] = "Hello, world!";return View(" MyView");
}
}
10 min: reuse the viewcontent
ViewData is another wayto pass data to the View
Controller code tends to followa basic pattern:
Receiving Input data(get/post) and Process DataOutput View/Data/File
MVC Web - controller 2
Controller Receiving Input Data
query string values
form values
parameters parsed from the incoming URL (routing)
There are three main ways to access that data
(1) Extract it from a set of context objects
string oldProductName = Request.Form["c ity"];
(2) Using Action Method Parameterspublic ActionResult ShowWeatherForecast(string city){}
(3) Invoking Model Binding Manually in an Action Method
public ActionResult SubmitEditedProduct(Student s){}
Passed from theview
MVC Web - controller input 1
(1) Extract it from a set of context objects
Request.QueryString NameValueCollection GET variables sent with this request
Request.Form NameValueCollection POST variables sent with this request
Request.Cookies HttpCookieCollection Cookies sent by the browser with this request
Request.HttpMethod string The HTTP method (verb, e.g., GET or POST) used for this request
Request.Headers NameValueCollection The full set of HTTP headers sent with this request
Request.Url Uri The URL requested
Request.UserHostAddress string The IP address of the user making this request
RouteData.Route RouteBase The chosen RouteTable.Routes entry for this request
RouteData.Values RouteValueDictionary Active route parameters (either extracted from the URL, or default values)
HttpContext.Application HttpApplicationStateBase Application state store
HttpContext.Cache Cache Application cache store
HttpContext.Items IDictionary State store for the current request
HttpContext.Session HttpSessionStateBase State store for the visitor’s session
User IPrincipal Authentication information about the logged-in user
TempData TempDataDictionary Temporary data items stored for the current user (more about this later)
MVC Web - controller input 2
(2) Using Action Method Parameters
public ActionResult ShowWeatherForecast(string City, DateTime forDate){
// instead of using Request.Form like following, use parameters// string city = Request.Form["city"];// DateTime forDate = DateTime.Parse(Request.Form["forDate"]);
}
"City" variable (case sensitive)
To supply values for your parameters, theMVC Framework scans severalcontext objects to find matching key/value pairs
Request.QueryString /index.aspx?id=12345
Request.Form <input type=text name="City">
RouteData.Values /Catalog/Red
Found
MVC Web - controller output 1
Output View/Data/File
Commonly used - Return a View
public ViewResult Index(){
return View("Homepage");}
Commonly used - Redirect to a new page
public RedirectToRouteResult SaveRecord(int itemId, string newName){
// … some process ...return RedirectToAction("Index");
}
Commonly used - Any action result
public ActionResult GiveMePlainText(){
return Content("This is plain text", "text/plain");}
Return a pdf file
public FilePathResult DownloadReport(){
string filename = @"c:\files\ somefile.pdf";return File(filename, "application/ pdf", "AnnualReport.pdf");
}
MVC Web - controller output 2
Output View/Data/File (JavaScript)
return JSON data
[HttpPost]public JsonResult WeatherData(){
var citiesArray = new[] {new CityData { city = "London", temperature = 68 },new CityData { city = "Hong Kong", temperature = 84 }
};
// [{"city":"London","temperature":68},{"city":"Hong Kong","temperature":84}]return Json (citiesArray);
}
return JavaScript
public JavaScriptResult SayHello(){
return JavaScript("alert('Hello, world!');");}
MVC Web - controller output 3
we have seen
// /Students/Create public ActionResult Create() {
StudentInfo student = new StudentInfo(100, "", "", ""); return View(student); }
*** ActionResult is an abstract of ViewResult
what's the difference between ViewResult and View
public ViewResult Index(){
return View("Homepage"); }
*** The Controller.View() method creates and passes a ViewResult objectto the ASP.NET MVC framework, which calls ViewResult.ExecuteResult()method to create the content
public ViewResult Index(){
return View("Homepage");// same as...return new ViewResult { ViewName = "Homepage" };
}
MVC Web - controller output 4
Controller output summary
MVC Web - View 1
WebFormViewEngine - The MVC Framework's built-in view engine.
Built on the existing Web Forms stack. Includes
Server controls (i.e., grid controls)
master pages (i.e., Views/shared/ site.master)
Visual Studio designer (drag & drop controls)
providing some additional ways to generate HTML (Html.Textbox())
Very simple view example:
@{ViewBag.Title = "Home Page";
}
<p> Welcome to CSE 136 MVC sample project..</p>
MVC Web - View 2
HTML Helpers
String-based HTML Helpers
MVC Web - View 3
HTML HelpersStrongly Typed Input Controls (improved syntax, that's all)
MVC Web - View 4
HTML Helpers
Rendering Links and URLs
not a link
not a link
not a link
defined route name in global.asax.cs
MVC Web - View 5
HTML HelpersRendering Drop-Down & listMultiselect
MVC Web - View 6
HTML HelpersRendering Forms
@using(Html.BeginForm("MyAction", "MyController")) {... form elements go here ...
}
Output:
<form action="/ MyController/ MyAction" method="post">... form elements go here ...
</form>
MVC Web - View 7Passing ViewData to View
Example of your class definition:
public class Person{
public string Name { get; set; }public int Age { get; set; }
}
In your controller:
public ViewResult Index(){
ViewData["message"] = "Hello World!";ViewData["personA"] = new Person { Name = "Maggie", Age = 2 };return View("SomeView");
} pass the class objectPerson to the view
In your " SomeView" page:
@{ Person a = ViewData["personA"]; }Name : @a.NameAge : @a.Age
MVC Web - View 8
Partial Views A Web Forms user control (i.e., an ASCX
file) Compiled as a class that inherits from
ViewUserControl (which in turn inherits from UserControl, the base class for all Web Forms user controls)
Break time
MVC Model will be in the demo
Demo
Service Layer code MVC tutorial MVC 136 solution – debugged mode
Model (including service call) View (including ascx) Site.Master Controller Unit Test
Review question
What are the 5 page class functions? Does the routing order matter? Where is the controller receiving its input value from? When do you use ViewData[“”]? What is the keyword to access the view model?
Your assignment
Due next Thursday GUI Implementation using ASP.NET MVC
3.0 Model, view, controller MVC Tests Write DTO between SL and PL in
Presentation Layer Must implement one user control (ascx)
of some kind (see 136 sample mvc3 project)
Use simple CSS if possible
References
.NET : Architecting Applications for the Enterprise
MVC 3.0
top related