ASP. NET mvc4.0 Getting Started Guide-Controller Access Model Data

Source: Internet
Author: User
Tags table definition actionlink connectionstrings

In this section, you will create a new moviescontroller class and write code to obtain the video data and use the view template to display the video data in the browser.
Before proceeding to the next step, click "generate application" to compile the application.
Right-click the controllers folder and create a controller named "moviescontroller. Shows the options in the create window.

Click Add to create the following files and folders:

  • Add the moviescontroller. CS file in the controllers folder of the project.
  • Add a movies folder under the views folder of the project.
  • Create. cshtml, delete. cshtml, details. cshtml, Edit. cshtml, and index. cshtml files are created in the views/movies folder.

ASP. net mvc 4 automatically generates CRUD (create, read, modify, and delete) operation methods and views for you (automatically create curd operation methods and views are often referred to as scaffolding ). Now you have a complete functional web application that displays the list and details of movies, creates, edits, and deletes movies.

Note: The automatically generated buttons and links are still in English. For example, if the newly created button is "create new", it is very uncomfortable. manually modify the button for the moment and find a permanent method, it is suggested that the language is either written in Chinese to the MVC language, or to modify the MVC source code implementation. From the perspective of the interface, the MVC has been written in Chinese, but it is not completely written in Chinese. It is certainly feasible to modify the MVC source code, let's talk about it later.

Run the application, append/movies in the browser address bar, and access the movies controller. Because the application depends on the default route (defined in the Global. asax file), the browser requests http: // localhost: XXXXX/movies to be routed to the index operation method of the default movies controller. In other words, the browser requests http: // localhost: XXXXX/movies and requests http: // localhost: XXXXX/movies/index have the same effect. Because you have not added any data, the current video list is empty.

Create a video

Note: first open index. cshtml and change @ html. actionlink ("create new", "CREATE") to @ html. actionlink ("new", "CREATE "). (Find the corresponding view template file and modify it later)

Click the "new" link to go to the film editing page. after entering the content, click the "new" button to send the form to the server, and the video information will be saved to the database. Go back to the list and you will see the created video in the list.

Note: The date format has backend verification. You can only pass the date format after entering the format 2012/12/05 ......

Create more film entities and try to edit, details, and delete all the links.

View automatically generated code

Open the controllers \ moviescontroller. CS file and view the generated index method.

public ActionResult Index(){  return View(db.Movies.ToList());}

The next line of the moviescontroller class declaration, private moviedbcontext DB = new moviedbcontext (), is a previously described context object of the video database. You can use this object to query, edit, and delete movies.

After receiving the request, the film controller returns all objects in the database film table and sends the result to the index view.

Strong model and @ model keywords
In the previous tutorial, I learned how controllers transmit data or objects to view templates through viewbag objects. Viewbag is a dynamic object that provides a convenient late binding method to transmit information to the view. ASP. net mvc also provides the ability to pass strong data or objects to view templates. The strong type method is more conducive to checking code during compilation and smart prompts in the Visual Studio editor. This method is used to process the moviescontroller class and view template When Visual Studio's scaffolding mechanism is created.

View the details method generated in the controllers \ moviescontroller. CS file. The Code is as follows:

        public ActionResult Details(int id = 0)        {            Movie movie = db.Movies.Find(id);            if (movie == null)            {                return HttpNotFound();            }            return View(movie);        }

If a video is found, the video model instance 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 expected object type of the view. When you create a Video Controller, Visual Studio automatically introduces the @ model statement at the top of the details. cshtml file:

@ Model enables you to directly access the strong model object passed by the Controller to the view. For example, in the details. cshtml template, the Code uses a strongly typed object to pass each field of the video to the displaynamefor and displayfor methods of HTML helpers. The create and edit methods and view templates also pass the film model object.

View the index. cshtml view template and the index method in the moviescontroller. CS file. Note: In the index method, how does the Code create a list object when called by the view helper method.

public ActionResult Index(){return View(db.Movies.ToList());}

When you create a Video 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 allows you to directly access the list of videos transmitted by the Controller through a strongly typed object. For example, in the index. cshtml template, the Code uses foreach to traverse a strong model object.

@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), every object type in the loop is movie. This means that all smart prompts in the Code and Code Editor are detected during compilation.

Use SQL Server local data
Note: In the above example, you may wonder where the entered video information is stored and whether it is stored in memory? Restart the web and find that the added information can still be saved, indicating that it is not the memory. Next let's talk about this problem.
If the connection string pointing to the video database does not exist in the Entity Framework code first mode, the database is automatically created. You can check the app_data folder to confirm that the database has been created. If you do not see the database file, click the "show all files" button in the Solution Explorer toolbar to refresh the file and expand the app_data folder. The file name is generally "mvcmovie. models. moviedbcontext. MDF, double-click this file, automatically open the server resource manager, expand the "table" folder, you will see the movie table.

Right-click the movie table and select "Open table definition" to view the object framework code first.

CREATE TABLE [dbo].[Movies] ([ID] INT IDENTITY (1, 1) NOT NULL,[Name] NVARCHAR (MAX) NULL,[Genra] NVARCHAR (MAX) NULL,[Price] DECIMAL (18, 2) 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 you created earlier. The Entity Framework code first automatically creates a table structure based on your movie class. To end viewing, right-click mvcmovie. Models. moviedbcontext and choose close connection. (If you do not close the connection, an error may occur when you run the project next time ).

Now the database is created and a simple list is displayed for obtaining data from it. In the next course, we will view the code generated by the remaining scaffolding and addSearchIndexThe method and view are used to query the video information in the database.

Note: How can I connect to a formal database instead of using a local database? In fact, I mentioned it at the end of the previous section in the original English tutorial. At that time, I thought it was too abrupt and the translator did not translate it in the previous section. I would like to add it here.

Moviedbcontext connects to the database and maps movie objects to database records. You may ask a question: how to specify the database to connect? This task is implemented by adding connection information to the Web. config file of the application.
Open the Web. config file in the root directory of the application (not the Web. config file in the view folder). The following example shows that the new connection string is 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 must be moviedbcontext, which is consistent with the class name.

 

Navigation of all articles in this tutorial

This series contains 10 articles 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.

The original article is for 9 articles, and the translator splits 6th of them into 2

1. Introduction to ASP. NET mvc4

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/intro-to-aspnet-mvc-4

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/03/2800210.html

2. Add a controller

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-controller

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/04/2801949.html

3. Add a view

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-view

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/04/2801988.html

4. Add a model

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-model

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/05/2803012.html

5. Access the data model from the Controller

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/accessing-your-models-data-from-a-controller

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/05/2803429.html

6. view the Edit Method and edit View

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/examining-the-edit-methods-and-edit-view

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/05/2804100.html

Http://www.cnblogs.com/seawaving/archive/2012/12/06/2804590.html

7. Add fields for the movie model and database table

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-new-field-to-the-movie-model-and-table

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/06/2805401.html

8. Add verification for the model

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-validation-to-the-model

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/06/2806322.html

9. view the detail and delete Methods

· Original 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/seawaving/archive/2012/12/10/2811064.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.