开发者

how to render dynamic list in ASP .NET MVC 2

ASP .NET MVC2 application.

Site.Master file contains number of ul list link names, url and url content is stored in database table

create table webconte(
   elemname char(20) not null,
   itemorder integer not null,
   caption char(40),
   webcontent text,
   primay key (elemname, itemorder) )

Number of elements in list and captions are h开发者_JAVA技巧ard coded in view like:

 <ul class="nav1"> 
  <li><a href='<%= Url.Action("WebContent", "Home", new { elemname="MainMenu", itemorder=0} ) %>'>caption1</a></li> 
  <li><a href='<%= Url.Action("WebContent", "Home", new { elemname="MainMenu", itemorder=1} ) %>'>caption2</a></li> 
  <li><a href='<%= Url.Action("WebContent", "Home", new { elemname="MainMenu", itemorder=2} ) %>'>caption3</a></li> 
</ul> 

WebContent action returns webcontent field value which contains html page.

How to create view so that:

  1. Number of items is not hard-coded: as many li elements as there are items in database are rendered.

  2. caption1, caption2, ... link texts are retrieved from webconte table caption column

This should be wrapped probalby to partial view to create re-usable component. I'm using MVC2 and C#.


In your controller, collect all your captions into a list of strings and put that list in ViewData. e.g.

var captions = new List<string>();
// add stuff to captions...
ViewData["captions"] = captions

Then on your page you can extract those captions and render your list:

<ul class="nav1">
<%
    var captions = ViewData["captions"] as List<string>();
    for (int i = 0; i < captions.Count; ++i) {
%>
    <li><a href='<%= Url.Action("WebContent", "Home", new { elemname="MainMenu", itemorder=i} ) %>'><%= captions[i] %></a></li>
<% } %>
</ul>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜