Home > Software engineering >  Looping through entire table makes problem with showing multiple values to an single element
Looping through entire table makes problem with showing multiple values to an single element

Time:11-21

I have little problem with dynamically add data to the HTML from SQL Table..

This is my loop

@foreach (var item in Model.ModulesSubStages)
{
    <div >
        <div ><a id="courseRedirect" asp-page="/Site/Courses/@item.ModuleId/@item.Id" > @item.StageName </a></div>
        <div >
            @foreach (var monit in Model.ProgressMonitor)
            {
                if (monit.UserId == Model._User.Id && item.Id == monit.CourseSubStageId)
                {
                    <i  id="@item.Id" style="color:green;"></i>
                }
                else if (monit.UserId == Model._User.Id && item.Id != monit.CourseSubStageId)
                {
                    <i  id="@item.Id" style="color:gray;"></i>
                }
                else
                {
                    <i  id="@item.Id" style="color:gray;"></i>
                }
            }
        </div>
    </div>
}

ModulesSubStages = 9 items

ProgressMonitor - table when i insert data after completing some action

Problem:

This loop result is:

enter image description here

I want to loop through entire table and mark green if it is completed, else gray, i dont want to print to the html multiple values per 1 record.

-- UPDATE

this is ProgressMonitor table structure:

SELECT [Id]
      ,[CourseId]
      ,[CourseStageId]
      ,[CourseSubStageId]
      ,[UserId]
  FROM [ProgressMonitor];

CodePudding user response:

You don't need to secound loop!

you just use a where clause instead

@foreach (var item in Model.ModulesSubStages)
{
<div >
    <div ><a id="courseRedirect" asp-page="/Site/Courses/@item.ModuleId/@item.Id" > @item.StageName </a></div>
    <div >
        @if (Model.ProgressMonitor.Any(a => a.UserId = Model._User.Id && item.Id == a.CourseSubStageId))
        {
            <i  id="@item.Id" style="color:green;"></i>
        }
        else
        {
            <i  id="@item.Id" style="color:gray;"></i>
        }
    </div>
</div>
}

CodePudding user response:

Change your codes as below;

@foreach (var item in Model.ModulesSubStages){
  <div >
  <div ><a id="courseRedirect" asp-page="/Site/Courses/@item.ModuleId/@item.Id" > @item.StageName </a></div>
  <div >
    @foreach (var monit in Model.ProgressMonitor)
    {
        if (monit.UserId == Model._User.Id )
        {
         if (item.Id == monit.CourseSubStageId )
           {
            <i  id="@item.Id" style="color:green;"></i>
           {
              break;
             }
           }
         else if (item.Id != monit.CourseSubStageId )
            {
            <i  id="@item.Id" style="color:gray;"></i>
             {
              break;
             }
            }
        }
        
    }
   </div>
  </div>
}
  • Related