1

On a View I am calling Render action with from within a loop, the action will create an array of objects and return to a PartialView with a Grid to display the results.

View:

foreach (var item in Model)
<%Html.RenderAction("GridData", "Customer", new {passidx = (new Random().Next(50))});%>

Controller:

public ActionResult GridData(int passidx)
    {
        List<Customer> cList = new List<Customer>{new Customer() { name = "c" + (1 + passidx).ToString(), address = "a" + (1 + passidx).ToString() },
                                                  new Customer() { name = "c" + (2 + passidx).ToString(), address = "a" + (2 + passidx).ToString() }};

        return View(cList);
    }

Roughly 2 out of every 3 times I refresh the page the values for each element in the grids are the same even though I am passing a random number to each Action which is appended to the displayed text.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
keitn
  • 1,288
  • 2
  • 19
  • 43

2 Answers2

2

instead of calling new Random() in foreach, declare one instance before foreach. you are getting duplicate because it is using same seed.

See this great answer.

Example:

Random random = new Random();
foreach (var item in Model)
<%Html.RenderAction("GridData", "Customer", new {passidx = (random.Next(50))});%>
Community
  • 1
  • 1
Adeel
  • 19,075
  • 4
  • 46
  • 60
  • It's noting to do with Random, if I change it to declare an Int and and increment it in the loop then pass this int exactly the same behaviour occurs – keitn Feb 17 '11 at 14:09
  • Further more if I put a break point in the controller the value is always the same even though debugging the view shows different values being passed. It's almost like the values are cached somewhere – keitn Feb 17 '11 at 14:15
  • @user621477 I have tried on my system (see example), and it's working fine. – Adeel Feb 17 '11 at 15:04
0

It looks like it's the scope of the variable that's causing the problem. If I declare Random or int or whatever inside the loop it doesn't work, moving it outside does.

keitn
  • 1,288
  • 2
  • 19
  • 43