ASP. NET MVC4.0 Official tutorial Getting Started Guide V-Controller Access model data
In this section, you will create a new Moviescontroller class and write code that implements the ability to get the movie data and use the view template to present the movie data in the browser.
Click Build application to compile the application before you proceed to the next step.
Right-click the Controllers folder and create a new controller named "Moviescontroller". In the Create window options as shown in
Click Add to create the following files and folders:
- Add MoviesController.cs file under the Controllers folder of the project
- New movies folder under the Views folder of the project
- Five files were created under the Views/movies folder create.cshtml, delete.cshtml, details.cshtml, edit.cshtml, and index.cshtml.
ASP. 4 automatically generates CRUD (create, read, modify, and Delete) operations methods and views for you (automatically creating curd action methods and views are often referred to as scaffolding). Now that you have a full-featured Web application, you can display a list of movies and details, create a movie, edit a movie, and delete a movie.
Run the application, attach/movies in the browser address bar, and access the Movies controller. Because the application relies on the default route (defined in the Global.asax file), the browser requests that http://localhost:xxxxx/Movies be routed to the default movies Controller's index action method. In other words, the browser request http://localhost:xxxxx/Movies the same effect as the request Http://localhost:xxxxx/Movies/Index. Because you haven't added any data, the current movie list is empty.
View Auto-generated code
Open the Controllers\moviescontroller.cs file to view the resulting index method
Public ActionResult Index () {return View (db. Movies.tolist ());}
The next line of the Moviescontroller class declaration is private Moviedbcontext db = new Moviedbcontext (); is a movie Database context object described previously, and you can use this object to query, edit, and delete movies.
After the movie controller receives the request, it returns all the entities in the Database movie table and passes the results to the index view.
Strongly typed models and @model keywords
In the previous tutorial, you learned how a controller can pass data or objects to a view template through a ViewBag object. ViewBag is a dynamic object that provides a convenient late binding way to pass information to a view. ASP. NET MVC also provides the ability to pass strongly typed data or objects to a view template. A strongly typed approach is more advantageous for compile-time detection code and smart hints in the Visual Studio editor. The scaffolding mechanism of Visual studio creates methods and views in this way to handle the Moviescontroller class and view templates.
View the details method generated in the next Controllers\moviescontroller.cs file. The code is as follows:
Public ActionResult Details (0) { movie movie = db. Movies.find (ID); nullreturnreturn View (movie);
If a movie is found, an instance of the movie model is passed to the detail view. Take a look at the contents of the views\movies\details.cshtml file.
By introducing the @model MvcMovie.Models.Movie statement at the top of the view template file, you can specify the object type that the view expects. When you create a movie controller, Visual studio automatically is in details. The @model statement is introduced at the top of the cshtml file:
@model gives you direct access to strongly typed model objects passed to the view by the controller. For example, in the details.cshtml template, code uses strongly typed objects to pass each field of the movie to the Displaynamefor and Displayfor methods of the HTML Helpers.
The Create and edit methods and view templates also pass the movie model objects.
View the Index method in the Index.cshtml view template and the MoviesController.cs file. Note how the code creates a list object in the index method when it is called by the View helper method.
Public ActionResult Index () {return View (db. Movies.tolist ());}
When you create a movie controller, Visual studio automatically introduces the following @model statement at the top of the index.cshtml file: @model ienumerable<mvcmovie.models.movie>
The @model statement gives you direct access to the list of movies passed by the controller through a strongly typed object. For example, in the index.cshtml template, the code traverses a strongly typed model object through a foreach
The @foreach (var item in Model) {<tr><td> @Html. Displayfor (ModelItem = Item. Title) </td><td> @Html. Displayfor (ModelItem = Item. ReleaseDate) </td><td> @Html. Displayfor (ModelItem = Item. Genre) </td><td> @Html. Displayfor (ModelItem = Item. Price) </td><th> @Html. Displayfor (ModelItem = Item. Rating) </th><td> @Html. ActionLink ("edit", "edit", new {id=item.id}) | @Html. ActionLink ("Details", " Details ", {id=item.id}) | @Html. ActionLink (" delete "," delete ", {id=item.id}) </td></tr>
Because model objects are strongly typed (Ienumerable<movie> objects), each object type in the loop is Movie. This means that the compile-time detection code and full smart hints in the Code Editor.
Using SQL Server Local data
Translator Note: In the above example you may wonder, where does the information for the film be filled in, memory? Restart the web and find that the added information can still be saved, stating that it is not memory, the following is the problem.
The Entity Framework code advance mode detects that the connection string that points to the movie database does not exist, and the database is created automatically. You can verify that the database has been created by looking at the App_Data folder. If you do not see the database file, click the "Show All Files" button in the Solution Explorer toolbar to refresh the button, then expand the App_Data folder, the file name is generally "MvcMovie.Models.MovieDbContext.mdf", double-click the file, Open Server Explorer automatically, expand the Tables folder, and you will see the movie table.
Right-click the movie table and select Open Table definition to view the table structure that the Entity Framework code first created for you
CREATE TABLE [dbo]. [Movies] ([ID] INT IDENTITY (1, 1) not Null,[name] NVARCHAR (max) Null,[genra] NVARCHAR (max) Null,[price] DECIMAL (2) is not NULL , [Date] DATETIME not null,constraint [pk_dbo. Movies] PRIMARY KEY CLUSTERED ([ID] ASC));
Note how the movie table maps to the movie class that you created earlier. The Entity Framework code first automatically creates a table structure based on your movie class. To end the view, you need to select close connection by right-clicking MvcMovie.Models.MovieDbContext. (If you do not close the connection, you may get an error The next time you run the project).
The database is now created and the data is obtained from it showing a simple list. In the next lesson, we'll look at the rest of the scaffolding generated code and increase the name of the SearchIndex
method and view used to query the database for movie information.
Translator: How do I connect to a formal database instead of using a local database? In fact, at the end of the previous English-language tutorial, explained that at that time, it was too abrupt, the translator did not translate in the previous section, this supplement.
Moviedbcontext is responsible for connecting the database, mapping the movie object to the database record. You might ask a question, how do you specify which database to connect to? This is done by adding connection information to the application's Web. config file.
Open the Web. config file under the application root (not the Web. config file under the View folder), and the following example shows the new connection string being added:
<connectionstrings><add name= "defaultconnection" connectionstring= "Data source= (LocalDb) \v11.0;Initial catalog=aspnet-mvcmovie-2012213181139;integrated security=true "providername=" System.Data.SqlClient "/> <add Name= "Moviedbcontext" connectionstring= "Data source= (LocalDB) \v11.0; attachdbfilename=| datadirectory|\movies.mdf;integrated security=true "providername=" System.Data.SqlClient "/> </ Connectionstrings>
Note that the key value needs to be moviedbcontext, consistent with the class name.
ASP. NET MVC4.0 Official tutorial Getting Started Guide V-Controller Access model data