RenderAction 的奇怪行为

发布于 2024-10-17 14:52:03 字数 724 浏览 8 评论 0原文

在视图上,我在循环内调用渲染操作,该操作将创建一个对象数组并返回到带有网格的 PartialView 以显示结果。

视图:

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

控制器:

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

大约每 3 次刷新页面就有 2 次,网格中每个元素的值都是相同的,即使我将随机数传递给附加到显示文本的每个操作。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

睫毛上残留的泪 2024-10-24 14:52:03

不要在 foreach 中调用 new Random(),而是在 foreach 之前声明一个实例。你会得到重复的,因为它使用相同的种子。

请参阅这个很好的答案。

示例:

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

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))});%>
倚栏听风 2024-10-24 14:52:03

看来是变量的范围导致了问题。如果我在循环内声明 Random 或 int 或其他任何内容都不起作用,则将其移到外部即可。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文