odle
odle

Reputation: 5272

Shuffling divs using C# behindcode

I have an aspx page that has 10 divs. 6 of those divs need to be positioned at random every time the page refreshes. Those divs have a lot of content in them so I have to avoid doing this with javascript. I was told this could be achieved using the codebehind, which is in c#. Here is an idea:

protected void Page_Load(object sender, EventArgs e)
{
    var plantripsmall = new List<HtmlGenericControl> {
        div1, div2
    };

    DrawShuffled(plantripsmall);
}

public void DrawShuffled(List<HtmlGenericControl> orig)
{

    Random rnd = new Random();

    var shuffled = orig.OrderBy(s => rnd.Next()).ToList();

    int i = 0;
    while (i < orig.ToArray().Length)
    {
        orig[i].InnerHtml = shuffled[i].InnerHtml;
        i++;
    }
}

but that is not really working.

Cannot get inner content of div2 because the contents are not literal

and besides i would like to avoid controls

UPDATE The issue seems to be my include file inside that second div:

<div runat="server" id="div2">
<!--#include virtual="files/hello.aspx" -->
...more content
</div>

do you know how I would get past this issue?

Upvotes: 1

Views: 265

Answers (2)

Nilesh
Nilesh

Reputation: 2691

I am not sure why I don't get that error. just tried this and it works.

       HtmlGenericControl div1 = new HtmlGenericControl("div");
       HtmlGenericControl div2 = new HtmlGenericControl("div");
       div1.InnerHtml = "test1";
       div2.InnerHtml = "test2";
       var lst = new List<HtmlGenericControl>
       {
          div1,
          div2
       };
       Random rnd = new Random();

       var shuffled = lst.OrderBy(s => rnd.Next()).ToList();

        int i = 0;
        while (i < lst.ToArray().Length)
        {
            lst[i].InnerHtml = shuffled[i].InnerHtml;
            i++;
        }

        this.Controls.Add(div1);
        this.Controls.Add(div2);

Upvotes: 0

Joe Brunscheon
Joe Brunscheon

Reputation: 1989

You should really be using jQuery or some other client-side javascript to do this. I don't understand why you have a requirement that javascript won't work for this.

Upvotes: 2

Related Questions