ASP. NET mvc4 Getting Started Guide (5): Access data models from Controllers

Source: Internet
Author: User
Tags actionlink visual studio 2010

In this section, you create a newMoviescontrollerClass, 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 newMoviescontrollerController. 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 routedMoviesDefault ControllerIndexOperation 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 generatedIndexMethod. A part of movie controllers andIndexThe method is as follows.

Public ClassMoviescontroller: controller {PrivateMoviedbcontext DB =NewMoviedbcontext ();////Get:/movies/PublicActionresult index (){ReturnView (db. Movies. tolist ());}

 

Below isMoviescontrollerClass 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 ();

 

DirectionMoviesController request to returnMoviesAll records in the movie database table, and then pass the resultsIndexView.

Strong model and @ model keywords

In the previous tutorials of this series, you can see thatViewbagObject To pass data or objects from the Controller to the view template.ViewbagIt 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 usesMoviescontrollerClass and view template.

InControllers \ moviescontroller. CSFile to see the generatedDetailsMethod. In the movie controllerDetailsThe method is as follows.

 
PublicActionresult details (IntId =0) {Movie=DB. Movies. Find (ID );If(MOVIE =Null){ReturnHttpnotfound ();}ReturnView (movie );}

 

IfMovie,MovieThe instance of the model is passed to the Detail View. Take a lookViews \ movies \ details. cshtmlFile.

By introducing@ ModelStatement, you can specify the expected object type of the view. When you create a movie controller, Visual Studio@ ModelThe statement is automatically included inDetails. cshtmlFile top:

@ Model mvcmovie. Models. Movie

This@ ModelThe statement allows the ControllerModelThe object is passed to the view, so that you can access the passed strong-type movie model in the view. For exampleDetails. cshtmlTemplate,DisplaynameforAndDisplayforHTML helperModelEach 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. CSInIndexMethod. Note how the codeNdexIn the operation method, createListObject and callViewMethod.

This code is passed in the ControllerMoviesList to view:

 
PublicActionresult index (){ReturnView (db. Movies. tolist ());}

 

When you create a movie controller, Visual Studio express automatically includes@ ModelStatementIndex. cshtmlFile top:

@ Model ienumerable <mvcmovie. Models. Movie>

This@ ModelThe Declaration allows the Controller to set a list of strongly typed moviesModelThe object is passed to the view. For exampleIndex. cshtmlIn the templateModelObject usageForeachThe 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>}

 

BecauseModelThe object is strongly typed (YesIenumerable <movie>Object), so everyItemThe object type isMovieType. 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 pointsMoviesThe 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-clickMoviesTable and selectShow table dataTo view the data you have created.

Right-clickMoviesTable, selectOpen table definitionView the table structure of the table created by the Entity Framework code first.

Note howMoviesThe table structure of the table is mapped toMovieClass? The Entity Framework code is automatically created based onMovieThe 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 addSearchindexMethod andSearchindexView 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

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.