我有一个循环,并在html actionlink中将值分配给循环外部。但每次我提交链接时,只会将最后一个值输入actionlink。有人可以帮助我如何从循环中获取所有值。我的预期结果是当条件满足时,它将分配actionlinks类名 - 访问过,如果没有 - NotVisited。我在视图页面中有很多动作链接。
我的代码是 -
string[] class_name = null;
@foreach (string items in str_array)
// str_array I am getting like [0] = 1
// [1] = 2
{
if (items.ToString() == class_id.ToString())
// class id is integer value eg. 1 and getting from db
{
class_name = new string[] { "visited" };
}
else
{
class_name = new string[] { "NotVisited" };
}
}
@Html.ActionLink("test", "R_Class", "R_Class", null, new { @class = string.Format("{0}", class_name), onclick = "return false;" })
答案 0 :(得分:1)
您的问题有点模糊,但我假设您要分配找到的第一个访问过的课程(如果有的话)
var class_name = new string[] {}; // I changed this line just to comply with coding best practices
@foreach (string items in str_array)
// str_array I am getting like [0] = 1
// [1] = 2
{
if (items.ToString() == class_id.ToString())
{
class_name = new string[] { "visited" };
break;
}
else
{
class_name = new string[] { "NotVisited" };
}
}
@Html.ActionLink("test", "R_Class", "R_Class", null, new { @class = string.Format("{0}", class_name), onclick = "return false;" })
如果我的假设是正确的,并且如果没有在课堂上访问过'它应该是“不受欢迎的”'然后你可以得到一个不那么冗长的代码:
var class_name = new string[] { "NotVisited" };
@foreach (string items in str_array)
{
if (items.ToString() == class_id.ToString())
{
class_name = new string[] { "visited" };
break;
}
}
@Html.ActionLink("test", "R_Class", "R_Class", null, new { @class = string.Format("{0}", class_name), onclick = "return false;" })
答案 1 :(得分:0)
我不知道你为什么要这样做,但看起来你想多次申请课程。
string[] class_name = null;
@foreach (string items in str_array)
{
if (items.ToString() == class_id.ToString())
{
class_name += " visited";
}
else
{
class_name += " NotVisited"
}
}
@Html.ActionLink("test", "R_Class", "R_Class", null, new { @class = string.Format("{0}", class_name), onclick = "return false;" })