[Official tutorial] Asp. Net MVC4 Getting Started Guide (5): Access data models from controllers, mvc4 Getting Started Guide
In this section, you create a newMoviesController
Class, and write code in the Controller class to obtain the movie data, and use the view template to display the data in the browser.
Before starting the next step, Build the application (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 class MoviesController : Controller{ private MovieDBContext db = new MovieDBContext(); // // GET: /Movies/ public ActionResult Index() { return View(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.
private MovieDBContext db = new MovieDBContext();
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.
public ActionResult Details(int id = 0){ Movie movie = db.Movies.Find(id); if (movie == null) { return HttpNotFound(); } return View(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
And DisplayFor HTML 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:
public ActionResult Index(){ return View(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 must install the SQL Server data tool and LocalDB. 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. Accessing the data model from the Controller is an important part of MVC data transmission. Only by understanding this part can MVC development be better. Of course, some development tools help the development process. The ComponentOne Studio ASP. net mvc lightweight control greatly improves the work efficiency and reduces the workload.