Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Thomas Beckert 193 posts 469 karma points
    Feb 16, 2018 @ 11:25
    Thomas Beckert
    0

    Random Integer Value in PartialView Macro

    Hi,

    I have a macro, that renders a contact formular. If the user insert the macro several times on the page, I want to give each macro a unique id for their input-fields, so that my javascript code know which input-field to check.

    I thought this would be very easy:

    @{   
    Random rnd = new Random();
       string rndInt = rnd.Next(5000, 10000).ToString();
    
    }
    <div class="agent-form">
        <form role="form" id="form-contact-agent_@rndInt" method="post" class="clearfix">
    
        ...
    
        <input type="text" class="form-control" id="name_@rndInt" name="name_@rndInt" required="">
        ...
    
        </form>
    </div>
    

    I put two macros per Grid-Insert Macro Selector on the page. Both macros render with the same random Integer. Cache for the macro is not activated of course.

    So did I do something wrong or is it an umbraco-performance issue, that same macro-source is only rendered once?

  • Streety 358 posts 568 karma points
    Feb 16, 2018 @ 19:25
    Streety
    100

    OK, Why don't you create a helper class to handle this. Something like this:

    Random rnd = new Random((int)DateTime.Now.Ticks);
    int RandomNumber;
    RandomNumber = rnd.Next(100000, 999999);
    

    and call it from your view

  • Thomas Beckert 193 posts 469 karma points
    Feb 19, 2018 @ 10:10
    Thomas Beckert
    0

    Hi Streety,

    thanks for the hint.

    This one does the trick:

    @functions
    {
        public int getRandomNumber()
        {
            Random rnd = new Random((int)DateTime.Now.Ticks);
            int RandomNumber;
            RandomNumber = rnd.Next(100000, 999999);
            return RandomNumber;
        }
    }
    
Please Sign in or register to post replies

Write your reply to:

Draft