RenderAction 的奇怪行为
在视图上,我在循环内调用渲染操作,该操作将创建一个对象数组并返回到带有网格的 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要在
foreach
中调用new Random()
,而是在foreach
之前声明一个实例。你会得到重复的,因为它使用相同的种子。请参阅这个很好的答案。
示例:
instead of calling
new Random()
inforeach
, declare one instance beforeforeach
. you are getting duplicate because it is using same seed.See this great answer.
Example:
看来是变量的范围导致了问题。如果我在循环内声明 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.