Download presentation
Presentation is loading. Please wait.
Published byJulianna Bond Modified over 9 years ago
1
BIT 286: Web Applications Lecture 04 : Thursday, January 15, 2015 ASP.Net MVC - Models
2
First Steps With Model http://www.asp.net/mvc/overview/getting-started/introduction/adding-a-model http://www.asp.net/mvc/overview/getting-started/introduction/adding-a-model (This was moved from the prior lesson to here – we’ll go through this as a class) Setting up the POCO / POJO, managed DB access Custom connection (to LocalDB, but could be to elsewhere) Scaffolding: Free CRUD! Examining the index page 2
3
EF sets up your DB with “Code First” “The Entity Framework (often referred to as EF) supports a development paradigm called Code First. Code First allows you to create model objects by writing simple classes. (These are also known as POCO classes, from "plain-old CLR objects.") You can then have the database created on the fly from your classes, which enables a very clean and rapid development workflow.” –Getting Started With MVCGetting Started With MVC Database first is still an option 3
4
C# Class definition Create a plain old CLR object (a normal class) in the Models folder public class Movie { public int ID { get; set; } public string Title { get; set { if( value == null || value == “”) throw new Exception(“blah”); this.Title = value; } } public DateTime ReleaseDate { get; set; } public string Genre { get; set; } public decimal Price { get; set; } } These are C# Properties “We'll use the Movie class to represent movies in a database. Each instance of a Movie object will correspond to a row within a database table, and each property of the Movie class will map to a column in the table.” 4
5
DB Context Add the following to the Movie.cs file: using System.Data.Entity; // add to top of file /* LOTS OF STUFF */ public class MovieDBContext : DbContext { public DbSet Movies { get; set; } } 5
6
Custom DB Connection String http://www.asp.net/mvc/overview/getting-started/introduction/creating-a-connection- string http://www.asp.net/mvc/overview/getting-started/introduction/creating-a-connection- string LocalDB Good for development, bad for deployment Can migrate the DB to a ‘real’ DB in the production environment In web.config we can store DB connection strings, based on the DbContext subclass name When ASP.Net MVC wants to get objects(rows) from the DB, it’ll use this connection Find the ROOT web.config, add the following to the connectionStrings element: name must the same as the DbContext subclass 6
7
Build the project So that the various classes have all been compiled, work ok, and VS can therefore examine them (programmatically) Notice that the DB doesn’t exist yet Note that the App_Data folder is still empty This will be auto-created for you when you run it 7
8
Working with SQL Server LocalDB Entity Framework will auto-create the DB for you if it doesn’t already exist It’ll examine the C# objects that are models & define SQL tables for them, create the overall DB, and create the individual tables. EF will also generate the code to automatically query, update, etc records In App_Data, EF will put a file named ‘Movies.mdf’ Double-click on it to start the Server Explorer Explore this now, on your own (and/or follow along with the tutorial web page) 8
9
Fun side-note “You don't actually need to add the MovieDBContext connection string. If you don't specify a connection string, Entity Framework will create a LocalDB database in the users directory with the fully qualified name of the DbContext class (in this case MvcMovie.Models.MovieDBContext). You can name the database anything you like, as long as it has the.MDF suffix. For example, we could name the database MyFilms.mdf.” 9
10
Bringing it all together: scaffolding CRUD http://www.asp.net/mvc/overview/getting-started/introduction/accessing- your-models-data-from-a-controller http://www.asp.net/mvc/overview/getting-started/introduction/accessing- your-models-data-from-a-controller Back in the Controllers folder, add a controller MVC 5 Controller with views, using Entity Framework Model Class: Movie Data context class: MovieDBContext “ Visual Studio creates the following files and folders: A MoviesController.cs file in the Controllers folder. A Views\Movies folder. Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml, and Index.cshtml in the new Views\Movies folder. ” 10
11
Take it for a spin http://localhost:58381/Movies/ http://localhost:58381/Movies/ Index lists all the objects, in a nifty table You can ‘Create New’ to add objects For each object you can: View details (a specific page with the same info, but bigger layout) Edit the object Delete the object Ways to use this: Consulting: generate pages to demonstrate basic stuff to the client Start here, then go back and modify the HTML / etc so that it actually looks nice 11
12
Examining the Details page The ViewBag thing was convenient… … but also error-prone (there’s no way for the compiler to check that any given field will actually exist when executing the View) A “Strongly typed” approach would be better At compile-time we use an object from a specific class Now compiler can check (in the View) if a given method/property actually exists 12
13
Examining the Details page public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Movie movie = db.Movies.Find(id); if (movie == null) { return HttpNotFound(); } return View(movie); } 13 This is like SELECT * FROM WHERE Note that we’re now passing this specific object to the View.
14
Examining the Details’ VIEW page @model MVCBasics.Models.Movie @{ ViewBag.Title = "Details"; } Details Movie @Html.Display Name For(model => model.Title) @Html.DisplayFor(model => model.Title) 14 This will print out the field’s name. (In this case, ‘Title’) This will print out the field’s value. (For example ‘Scary Movie’) This where we tell the view which C# type to expect
15
Examining the Details’ VIEW page @Html.Display Name For(model => model.Title) @Html.DisplayFor(model => model.Title) 15 These are lambda expressions. Essentially they’re implied, local, “micro” functions.
16
Lambda Functions (Brief Overview) model => model.Title This is actually a very concise function definition. You can think of this as saying something like: public string MyNewLambdaFnx(Movie model) { return model.Title; } UNLIKE a normal method, you can pass a lambda function as a parameter (i.e., you can treat it kinda like data) UNLIKE a normal method, these are ‘anonymous’ there’s no actual name More info at https://msdn.microsoft.com/en- us/library/bb397687.aspxhttps://msdn.microsoft.com/en- us/library/bb397687.aspx 16
17
Examining the Index page // GET: /Movies/ public class MoviesController : Controller { private MovieDBContext db = new MovieDBContext(); public ActionResult Index() { return View(db.Movies.ToList()); } 17 This is like ‘SELECT *” This object connects to the database
18
Examining the Index page In the controller file: public ActionResult Index() { return View(db.Movies.ToList()); } In the view file: @model IEnumerable // Stuff left out… @foreach (var item in Model) { @Html.DisplayFor(modelItem => item.Title) @Html.DisplayFor(modelItem => item.ReleaseDate) 18
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.