JMorgan JMorgan - 1 month ago 12
ASP.NET (C#) Question

ASP.NET web form pass list to view page and display with html controls

I am new in asp.net. I am trying to a static list pass into my view page.

Following code I have written on my _Default class:

protected void Page_Load(object sender, EventArgs e)
{
List<String> itemlist = new List<string>();
itemlist.Add("Drink water");
itemlist.Add("Sleep more");
itemlist.Add("Drink tea");
itemlist.Add("Drink water");
itemlist.Add("Exercise more");
itemlist.Add("Eat healthier");
itemlist.Add("Smile");
itemlist.Add("Do Yoga");
}


Now I am trying to pass above list into my Default.aspx page but I am not sure how to do that.

Please let me know how I can pass and display above list into my Default.aspx with HTML controls.

Answer

At first wrap your list with a function then call it from anywhere it's needed.

  public List<String> MyToDOList()
    {

        List<String> itemlist = new List<string>();
        itemlist.Add("Drink water");
        itemlist.Add("Sleep more");
        itemlist.Add("Drink tea");
        itemlist.Add("Drink water");
        itemlist.Add("Exercise more");
        itemlist.Add("Eat healthier");
        itemlist.Add("Smile");
        itemlist.Add("Do Yoga");

        return itemlist;
    }

Followings are sample code if you would like to display your lists with html tag on your .aspx file:

<%
    var todo_list=MyToDOList();
    Response.Write("<ul>");
    foreach(var item in todo_list)
    {
        Response.Write("<li>"+item+"</li><br/>");
    }
    Response.Write("</ul>");
    %>
Comments