Domanda

Im using Visual Studio 2012 and creating a web page using "ASP.NET Web Site (Razor v2)" Im using Java to generate a random link;

<script>
 var random = new Array();
 random[0] = "example1.com";
 random[1] = "pattern1.com";
 random[2] = "specimen1.com";
</script>

<script>
    function randomlink() {
        window.location = random[Math.floor(Math.random() * random.length)];
    }
</script>

<a href="javascript:randomlink()" style="color: black;">A Random URL</a>

When I click the A Random URL link it opens a random page from the list in the script above. I'ts all good, but because its a verry big list I need a way to do the same without having it in HTML because its slowing the loading of the page since its in the _SiteLayout.cshtml. Thanks.

È stato utile?

Soluzione

Among your choices are the following options:

  1. Send all the URLs to the client and have the client pick a random choice.
  2. Have the server pre-pick the random URL and send only that one to the client (it can just be put directly into the <a> link. No need for javascript at all.
  3. Make an ajax call to the server to request a random link and when that is returned, go to it.
  4. Make a get request to the server and have the server return a redirect to a randomly chosen URL.

It sounds like you don't want to implement the first option if you have a zillion URLs.

The second option is probably the easiest as it requires only slightly modifying the generation of the page and requires no new server APIs. You just have to figure out how to select a random URL in your server-side environment.

The third and fourth options are the least efficient as they require a call to the server, a response from the server with the new URL and then a client redirect to the actual URL.

Altri suggerimenti

I would pass the random url with the page when it renders from the server. You can generate the url on the server using c#'s Random class.

<a href='@Model.RandomUrl' style="color: black;">A Random URL</a>

Just pass a model that you reference in your view.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top