在我对.Net MVC5的有限经验中,我尝试编写以下代码:
<div class="row ">
@foreach (var item in Model)
{
string[] parm = new string[] { "btn-primary", "btn-success", "btn-info", "btn-warning", "btn-danger" };
Random r = new Random();
string temp = parm[r.Next(0, parm.Length)];
<div class="col-md-4" style="margin:10px 0">
<div class="card text-center">
<div class="card-header">
@Html.DisplayFor(modelItem => item.Type)
</div>
<div class="card-block" style="margin:10px 0;">
<h4 class="card-title" style="margin:10px 0"> @Html.DisplayFor(modelItem => item.Name)</h4>
<p class="card-text" style="height:40px;"> @Html.DisplayFor(modelItem => item.Description)</p>
<a href="@Html.DisplayFor(modelItem => item.URL)" class="btn @temp btn-sm" style="width:150px;margin:10px 0;">Get it</a>
</div>
</div>
</div>
}
</div>
我定义了一个随机变量[temp],我希望每个按钮都是随机的,但它没有显示不同的样式,我在哪里犯了错误?提前谢谢。
答案 0 :(得分:2)
请在循环外创建Random r = new Random();
。使用当前时间初始化Random
类。 Foreach
循环很快,因此每个Random
实例都以相同的值播种。
这里有一些细节:How do I seed a random class to avoid getting duplicate random values
@{
Random r = new Random();
foreach (var item in Model)
{
string[] parm = new string[] {"btn-primary", "btn-success", "btn-info", "btn-warning", "btn-danger"};
string temp = parm[r.Next(0, parm.Length)];
<div class="col-md-4" style="margin: 10px 0">
<div class="card text-center">
<div class="card-header">
@Html.DisplayFor(modelItem => item.Type)
</div>
<div class="card-block" style="margin: 10px 0;">
<h4 class="card-title" style="margin: 10px 0"> @Html.DisplayFor(modelItem => item.Name)</h4>
<p class="card-text" style="height: 40px;"> @Html.DisplayFor(modelItem => item.Description)</p>
<a href="@Html.DisplayFor(modelItem => item.URL)" class="btn @temp btn-sm" style="width: 150px; margin: 10px 0;">Get it</a>
</div>
</div>
</div>
}
}