0

Working on a project where I simply need to generate a random number using NVelocity in a page without editing the code behind C#. I'm new to NVelocity and I've looked all over the interwebs but cant't find the answer.

Any help is appreciated.

NOTE: To the user who marked this as a possible duplicate question. I've tried to adapt the Velcocity/Java solution listed in that answer to fit NVelocity/C# with no luck. I was under the assumption the answer would be different.

GeekInTheBox
  • 139
  • 2
  • 11
  • 1
    Possible duplicate of [Velocity - random number generation in a template](http://stackoverflow.com/questions/24758937/velocity-random-number-generation-in-a-template) – Andrew Morton Aug 16 '16 at 19:06

1 Answers1

0

NVelocity doesn't have built-in support for generating pseudo-random numbers, however if you create a new System.Random and add it to the VelocityContext you'll be able to access it from the template.

VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.Init();

VelocityContext context = new VelocityContext();
context.Put("random", new Random());

using (StringWriter sw = new StringWriter())
{
    for (int i = 0; i < 5; i++)
    {
        velocityEngine.Evaluate(context, sw, "", "$random.Next(1, 100)\n");
    }

    Console.WriteLine(sw.ToString());
}
Jonathon Rossi
  • 4,149
  • 1
  • 22
  • 32