In this section, you create a newMoviescontroller
Class, and write it in this controller classCodeTo obtain the movie data, and use the view template to display the data in the browser.
Build the application before proceeding to the next step.Program(Generate an application)(Ensure that the Application compilation is correct)
Right-click the Controller folder and create a newMoviescontroller
Controller. After the build is successful, the following options are displayed. Set the following options:
· Controller Name:Moviescontroller. (This is the default value ).
· Template:MVC controller with read/write actions and views, using Entity Framework.
· Model class:Movie (mvcmovie. Models).
· Data context:Moviedbcontext (mvcmovie. Models).
· Opinions:Razor (cshtml ).(Default ).
ClickAdd. Visual Studio express creates the following files and folders:
· Moviescontroller. CS file in the project controller folder.
· Movie folder under the project view folder.
· Create. cshtml, delete. cshtml, details. cshtml, Edit. cshtml, and index. cshtml files in the new views \ movies folder.
ASP. net MVC 4 automatically creates CRUD (create, read, update, and delete) operation methods, and related view files (crud automatically creates operation methods and view files are called infrastructure files ). Now you have all the web functions to create, list, edit, and delete movie entity.
Run the application and append/movies to the URL of the browser address bar to browse the movies controller. Because the application depends on the default route (Global. asaxFile), browser requestHttp: // localhost: XXXXX/moviesWill be routedMovies
Default ControllerIndex
Operation Method. In other words, browser requestsHttp: // localhost: XXXXX/moviesEquivalent to browser requestsHttp: // localhost: XXXXX/movies/Index. Because you have not added any content, the result is an empty movie list.
Create a movie
ClickCreate newLink. Enter details about the movie, and then clickCreateButton.
ClickCreateThe button will make the form submitted to the server, and the movie information will be saved to the database. Then you will be redirected to URL/movies. You can see the new movie you just created in the list.
Create more movie data. You can also clickEdit,DetailsAndDeleteFunction link.
Let's take a look at the generated code.
OpenControllers \ moviescontroller. CSFile, and find the generatedIndex
Method. A part of movie controllers andIndex
The method is as follows.
Public ClassMoviescontroller: controller {PrivateMoviedbcontext DB =NewMoviedbcontext ();////Get:/movies/PublicActionresult index (){ReturnView (db. Movies. tolist ());}
Below isMoviescontroller
Class to instantiate the context instance of the Movie Database, as described above. The Movie Database context instance can be used to query, edit, and delete movies.
PrivateMoviedbcontext DB =NewMoviedbcontext ();
DirectionMovies
Controller request to returnMovies
All records in the movie database table, and then pass the resultsIndex
View.
Strong model and @ model keywords
In the previous tutorials of this series, you can see thatViewbag
Object To pass data or objects from the Controller to the view template.Viewbag
It is a dynamic object and provides a convenient post-binding method to pass information to the view.
ASP. net mvc also provides the ability to transmit strong data or objects to view templates. This strong type makes it easier to check your code during compilation and provides richer intelligent awareness in the Visual Studio editor. When creating operation methods and views, the infrastructure mechanism in Visual Studio usesMoviescontroller
Class and view template.
InControllers \ moviescontroller. CSFile to see the generatedDetails
Method. In the movie controllerDetails
The method is as follows.
PublicActionresult details (IntId =0) {Movie=DB. Movies. Find (ID );If(MOVIE =Null){ReturnHttpnotfound ();}ReturnView (movie );}
IfMovie
,Movie
The instance of the model is passed to the Detail View. Take a lookViews \ movies \ details. cshtmlFile.
By introducing@ Model
Statement, you can specify the expected object type of the view. When you create a movie controller, Visual Studio@ Model
The statement is automatically included inDetails. cshtmlFile top:
@ Model mvcmovie. Models. Movie
This@ Model
The statement allows the ControllerModel
The object is passed to the view, so that you can access the passed strong-type movie model in the view. For exampleDetails. cshtmlTemplate,Displaynamefor
AndDisplayforHTML helperModel
Each field of a movie is transmitted. Both the creation and editing methods and view templates are passing strong Model Objects of movies.
Take a lookIndex. cshtmlView templates andMoviescontroller. CSInIndex
Method. Note how the codeNdex
In the operation method, createList
Object and callView
Method.
This code is passed in the ControllerMovies
List to view:
PublicActionresult index (){ReturnView (db. Movies. tolist ());}
When you create a movie controller, Visual Studio express automatically includes@ Model
StatementIndex. cshtmlFile top:
@ Model ienumerable <mvcmovie. Models. Movie>
This@ Model
The Declaration allows the Controller to set a list of strongly typed moviesModel
The object is passed to the view. For exampleIndex. cshtmlIn the templateModel
Object usageForeach
The statement traverses the movie list cyclically:
@ 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>}
BecauseModel
The object is strongly typed (YesIenumerable <movie>
Object), so everyItem
The object type isMovie
Type. One of the benefits is that this means you can check the code during compilation and support more comprehensive intelligent awareness in the Code Editor:
Use SQL Server localdb
The Entity Framework code first code takes precedence. If no database connection string pointsMovies
The database is automatically created. Find it in the app_data folder and verify that it has been created. If you cannot seeMovies. MDFFileSolution Resource ManagerOn the toolbar, clickShow all filesClickRefreshAnd expand the app_data folder.
Double-clickMovies. MDFOpenDatabase Resource Manager, And then expandTableFolder to view the movie table.
Note: If the database resource manager is not displayed, you canToolsIn the menu, selectConnect to databaseAnd disableSelect data sourceDialog box. In this way, the database resource manager is forcibly opened.
Note: If you are using vWD or Visual Studio 2010, you may see an error message similar to the following:
· The database cannot be opened because the database 'C: \ webs \ mvc4 \ mvcmovie \ app_data \ movies. MDF 'is of version 706. This server supports databases of version 655 and earlier. It cannot be downgraded.
· The sqlconnection provided by "invalidoperation exception was unhandled by user code" does not specify the initial database.
You need to installSQL Server data toolsAndLocaldb. Verify the moviedbcontext connection string specified earlier.
Right-clickMovies
Table and selectShow table dataTo view the data you have created.
Right-clickMovies
Table, selectOpen table definitionView the table structure of the table created by the Entity Framework code first.
Note howMovies
The table structure of the table is mapped toMovie
Class? The Entity Framework code is automatically created based onMovie
The table structure of the class.
After you complete the operation, right-clickMoviedbcontext, SelectClose connectionClose the connection to the database. (If you do not close the connection, an error may occur when you run the project next time ).
Now, you can display the data in the database on the simple list page. In the next tutorial, we will continue to look at other code automatically generated by the framework. And addSearchindex
Method andSearchindex
View so that you can search for movies in the database.
Download the complete document:ASP. NET mvc41_1_timeout
Bytes --------------------------------------------------------------------------------------------------------------------
Note:
9 articles in this seriesArticle, Translated from ASP. net mvc4 official tutorial, due to the concise description of this series of articles, the length is moderate, from an example to explain, the full text finally completed a small system for managing movies, very suitable for beginners ASP.. Net mvc4. Nine articles:
1. Introduction to ASP. NET mvc4
· Original article address:Http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/intro-to-aspnet-mvc-4
· Translation address:Http://www.cnblogs.com/powertoolsteam/archive/2012/11/01/2749906.html
2. Add a controller
· Original article address:Http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-controller
· Translation address:Http://www.cnblogs.com/powertoolsteam/archive/2012/11/02/2751015.html
3. Add a view
· Original article address:Http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-view
· Translation address:Http://www.cnblogs.com/powertoolsteam/archive/2012/11/06/2756711.html
4. Add a model
· Original article address:Http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-model
· Translation address:Http://www.cnblogs.com/powertoolsteam/archive/2012/12/17/2821495.html
5. Access the data model from the Controller
· Original article address:Http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/accessing-your-models-data-from-a-controller
· Translation address:Http://www.cnblogs.com/powertoolsteam/archive/2013/01/11/2855935.html
6. Verify the editing method and view
· Original article address:Http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/examining-the-edit-methods-and-edit-view
· Translation address:Http://www.cnblogs.com/powertoolsteam/archive/2013/01/24/2874622.html
7. Add new fields to the movie table and Model
· Original article address:Http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-new-field-to-the-movie-model-and-table
· Translation address:Http://www.cnblogs.com/powertoolsteam/archive/2013/02/26/2933105.html
8. Add a validator to the Data Model
· Original article address:Http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-validation-to-the-model
· Address: http://www.cnblogs.com/powertoolsteam/archive/2013/03/05/2944030.html
9. query details and delete records
· Original article address:Http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/examining-the-details-and-delete-methods
· Address: http://www.cnblogs.com/powertoolsteam/archive/2013/03/07/2948000.html
10. Third-party control studio for ASP. NET wijmo mvc4 tool Application
Address: http://www.cnblogs.com/powertoolsteam/archive/2013/05/09/3068699.html