keitn
keitn

Reputation: 1298

Weird behaviour with RenderAction

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.

Upvotes: 1

Views: 236

Answers (2)

keitn
keitn

Reputation: 1298

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.

Upvotes: 0

Adeel
Adeel

Reputation: 19228

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))});%>

Upvotes: 2

Related Questions