Overview
Under ASP. NET WebForm, the list data is displayed, often using server controls such as GridView, DataList, and so on. In the ASP. NET MVC Framework, we have two ways to display the data, one is to use the inline code, that is, to render using the <%=%> tag through the loop view data, and the other is to use the server control to bind the view data to the server control, such as ASP. 3.5 new control in the ListView.
Defining a Controller
The controller definition here is very simple, get all the post data, and then pass the data to the view
[CSharp]View Plaincopy
- Public class Blogcontroller:controller
- {
- [Controlleraction]
- public void Index ()
- {
- //Get all post data
- Blogrepository repository = new Blogrepository ();
- List<post> posts = repository. GetAll ();
- //Turn to view index, show post list
- Renderview ("Index", posts);
- }
- }
Define View
Add an index view and make it inherit from Viewpage<list<post>>.
1. Use the inline code display to cycle through the data and use the HtmlHelper method provided by ViewPage.
[HTML]View Plaincopy
- <h3>1. Using inline code </h3>
- <%=html.actionlink ("Home", new { action="Index"})%> |
- <div>
- <%foreach (post post in ViewData)
- {%>
- <div class="PostItem">
- <strong>title</strong;:<%=html.encode (post. Title)%></br>
- <strong>author</strong;:<%=html.encode (post. Author)%></br>
- <strong>pubdate</strong;:<%=html.encode (post. Pubdate.toshortdatestring ())%></br>
- <strong>content</strong;:<%=html.encode (post. Description)%></br>
- </div><br />
- <%}%>
- </div>
2. Using the server control ListView, write the following code:
[HTML]View Plaincopy
- <h3> Using the ListView control </h3>
- <asp:listview id="ListView1" runat= "server">
- <layouttemplate>
- <div>
- <asp:placeholder id="Itemplaceholder" runat="Server"/>
- </div>
- </layouttemplate>
- <ItemTemplate>
- <div class="PostItem">
- <strong>title</strong;:<%# Eval ("Title")%></ </br>
- <strong>author</strong;:<%# Eval ("Author")%></BR >
- <strong>pubdate</strong;:<%# Eval ("PubDate")%> </br>
- <strong>content</strong;:<%# Eval ("Description")%></ br>
- </div><br />
- </ItemTemplate>
- </asp:listview>
The data binding of the ListView in the background code is simply to bind the view data to the ListView and get the data from the database to the controller.
[CSharp]View Plaincopy
- Public partial class views_blog_index:viewpage<list<post>>
- {
- protected void Page_Load (object sender, EventArgs e)
- {
- This . Listview1.datasource = ViewData;
- This . Listview1.databind ();
- }
- }
Set PATH selection
Also we need to set the path selection
[CSharp]View Plaincopy
- void Application_Start (object sender, EventArgs e)
- {
- //Code that runs on application startup
- ROUTETABLE.ROUTES.ADD (
- New Route
- {
- URL = "[Controller]/[action].mvc",
- Defaults = new {action = "Index"},
- Routehandler = typeof (Mvcroutehandler)
- });
- }
Go to ASP. NET MVC display list data