Display data in a database table

Source: Internet
Author: User

The purpose of this tutorial is to show you how to display an HTML table of database data in ASP. net mvc. First, it introduces how to format database records directly in the view. Next, we will introduce how to use partial when formatting database records.

Create model class

We will display the set of records in the movies database table. The movies database table contains the following columns:

Column name

Data Type

Null value allowed

ID Int False
Title Nvarchar (200) False
Director Nvarchar (50) False
Datereleased Datetime False

 

To represent the movies table in our ASP. net mvc program, we need to create a model class. In this tutorial, we use Microsoft Entity Framework to create an object.

However, it is very important to understand that you can use different technologies in ASP. net mvc programs to interact with databases, including LINQ to SQL, nhib.pdf, or ADO. net.

Follow these steps to start the Object Data Model Wizard:

  1. In Solution Explorer, right-click the models folder and select "add" and "new item ".
  2. Select "data" type and selectADO. NET Entity Data ModelTemplate.
  3. Name your data modelMoviesdbmodel. edmxClick "add.

After you click "add", the "Object Data Model Wizard" dialog box appears (see figure 1). Follow these steps to complete the Wizard:

  1. InSelect model objectIn this step, selectGenerate from databaseOption.
  2. InSelect your data connectionIn this step, useMoviesdb. MDFData Connection and name itMoviesdbentities.ClickNext stepButton.
  3. InSelect your database objectIn this step, expand the "table" node and select the movies table. Enter namespaceModelsClickCompleteButton.

 

Figure 01: Create a LINQ to SQL class (click to view the full size)

After the "Entity Data Model Wizard" is completed, the "Entity Data Model Designer" appears. The designer displays the movies entity (see figure 2 ).

Figure 02: Entity Data Model Designer (click to view the full size)

We need to make minor changes before continuing. The model class generated by the object data wizard is namedMoviesUsed to represent the movies database table. Because we use the movies class to represent a specific movie, we need to change the class nameMovieInsteadMovies(Singular, not plural ).

On the designer interface, double-click the class name and change the class name from movies to movie. After the changes, clickSaveButton (floppy disk icon) to generate the movie class.

Create a movies Controller

Since we can already represent our database records, we can create a controller to return the collection of movies. In the Visual Studio Solution Explorer window, right-click the controllers folder and select a menu itemAdd, Controller(See figure 3 ).

Figure 03: Add the Controller menu (click to view the full size)

 Add ControllerAfter the dialog box is displayed, enter the Controller name moviecontroller (see figure 4). ClickAddButton to add a new controller.

Figure 04: Add controller dialog box (click to view the full size)

We need to modify the index () operation exposed by the movie controller to return a set of database records. See Code 1.

Code 1-controllers/moviecontroller. CS

using System.Linq;using System.Web.Mvc;using MvcApplication1.Models; namespace MvcApplication1.Controllers{    public class MovieController : Controller    {        //        // GET: /Movie/         public ActionResult Index()        {            var entities = new MoviesDBEntities();            return View(entities.MovieSet.ToList());        }     }}

In code 1, The moviesdbentities class is used to represent the moviesdb database. To use this class, you need to import the mvcapplication1.models namespace:

Using mvcapplication1.models;

ExpressionEntities. movieset. tolist ()Returns a group of all movies from the movies database table.

Create View

The easiest way to display a set of database records in an HTML table is to use the scaffolding provided by Visual Studio.

Select menu itemsGenerate and generate solutionsRun your program. OpenAdd ViewYou must generate your program before the dialog box. Otherwise, your data class will not be displayed in the dialog box.

 

Right-click the index () operation and select a menu item.Add View(See figure 5 ).

Figure 05: Add a view (click to view the full size)

InAdd ViewIn the dialog box, selectCreate a stronugly-typed View. Select the movie classView data class. SelectListAsView content(See figure 6). Selecting these options will generate a strong view that displays a group of movies.

Figure 06: Add view dialog box (click to view the full size)

ClickAddButton. The view of Code 2 is automatically generated. This view contains the code to traverse the movies set and display each attribute of movie.

Code 2-views/movie/index. aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcApplication1.Models.Movie>>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">      Index</asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">     <p>Index</p>     <table>        <tr>            <th></th>            <th>                Id            </th>            <th>                Title            </th>            <th>                Director            </th>            <th>                DateReleased            </th>        </tr>     <% foreach (var item in Model) { %>           <tr>            <td>                <%= Html.ActionLink("Edit", "Edit", new { id=item.Id }) %> |                <%= Html.ActionLink("Details", "Details", new { id=item.Id })%>            </td>            <td>                <%= Html.Encode(item.Id) %>            </td>            <td>                <%= Html.Encode(item.Title) %>            </td>            <td>                <%= Html.Encode(item.Director) %>            </td>            <td>                <%= Html.Encode(String.Format("{0:g}", item.DateReleased)) %>            </td>        </tr>       <% } %>     </table>     <p>        <%= Html.ActionLink("Create New", "Create") %>    </p> </asp:Content>

You can select a menu itemDebug and start debugging(Or press F5) to run your program. The program starts Internet Explorer. If you navigate to the/movie URL, you will see the page 7.

Figure 07: Movie table (click to view the full size)

If you do not like the style of the database table in figure 7, you can simply modify the index view. For example, you canDatereleasedChange the headerDate released.

Use partial to create a template

It is a good idea to split a view into parts when it becomes too complex. Use partials to make your view easier to understand and maintain. We will create a partial as a template to format each Movie Database record.

Follow these steps to create a partial:

  1. Right-click the views/movie folder and choose a menu item.Add View.
  2. SelectCreate a partial view (. ascx).
  3. Name itMovietemplate.
  4. SelectCreate a stronugly-typed View.
  5. View data classSelect the movie class.
  6. View contentSelect empty.
  7. ClickAddClick Add partial to your project.

After completing these steps, modify movietemplate partial to make it as code 3.

Code 3-views/movie/movietemplate. ascx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcApplication1.Models.Movie>" %> <tr>    <td>        <%= Html.Encode(Model.Id) %>    </td>    <td>        <%= Html.Encode(Model.Title) %>    </td>    <td>        <%= Html.Encode(Model.Director) %>    </td>    <td>        <%= Html.Encode(String.Format("{0:g}", Model.DateReleased)) %>    </td></tr>

The partial in code 3 contains a single record template.

In code 4, the modified index view uses movietemplate partial.

Code 4-views/movie/index. aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcApplication1.Models.Movie>>" %> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">     <p>Index</p>     <table>        <tr>            <th>                Id            </th>            <th>                Title            </th>            <th>                Director            </th>            <th>                DateReleased            </th>        </tr>     <% foreach (var item in Model) { %>           <% Html.RenderPartial("MovieTemplate", item); %>       <% } %>     </table> </asp:Content>

The view in code 4 contains a foreach loop that traverses all movies. For each movie, movietemplate partial is used to format the movie. Movietemplate is rendered by calling the renderpartial () helper method.

The modified index view displays HTML tables with identical database records. However, the view is greatly changed.

The renderpartial () method is different from most other helper methods because it does not return a string. Therefore, you must use <% html. renderpartial (); %> instead of <% = html. renderpartial (); %> to call the renderpartial () method.

Address: http://www.asp.net/learn/mvc/tutorial-11-cs.aspx

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.