3

I am new to MVC and I want to display name of a user in two columns in a WebGrid as display below.

enter image description here

Currently the web grid display data in below format.

enter image description here

I am binding my WebGrid with List<string>, list contains username.

My Controller

public ActionResult Index()
{ 
    List<string> userList = new List<string>();
    userList.Add("User1");
    userList.Add("User2");
    userList.Add("User3");
    userList.Add("User4");
    return View(userList);
}

My Cshtml

@using (Html.BeginForm())
{
    var grid = new WebGrid(Model);
    @grid.GetHtml(columns: grid.Columns(grid.Column(format: (item) => item)));
}
RBT
  • 24,161
  • 21
  • 159
  • 240
  • so essentially you want to break your row after every two users. Correct? if you had 6 rows then there will be three rows in all. Correct? – RBT May 26 '17 at 08:45
  • Any reason you are not showing any header in your table? – RBT May 26 '17 at 09:03
  • I'm getting a feeling that webGrid is a wrong choice.In your list each string represents one record which in essence is a row. You should rather write simple loop along with table html elements to get the desired outcome. – RBT May 26 '17 at 09:44
  • Thank you for the response. Correct I have to break row after every two records. It is a requirement to not show any headers, just display Users. It will be a great help if you please suggest me how do I achieve a desire outcome with loop in a table. –  May 27 '17 at 12:12
  • Ohh.. then it is pretty straightforward. Let me add an answer right away. – RBT May 27 '17 at 14:59

1 Answers1

1

Your desired output is not the right use-case for a webgrid control. Here is the table generation logic for mvc razor view using simple for loop:

@model List<string>
<table >
            @{ 
                for (int i = 1; i <= Model.Count; i++)
                {
                    if (i % 2 != 0)
                    {
                        @:<tr >
                    }
                    <td style="border:solid;">
                            @Model[i - 1]
                    </td>

                     if (i % 2 == 0)
                     {
                         @:</tr>
                     }
                  }
              }
    </table>

I've added a css style style="border:solid;" just to show border of all the table cells. You can customize it as per your needs.

This code creates below table:

enter image description here

RBT
  • 24,161
  • 21
  • 159
  • 240
  • Thanks for the solution it really helps me. –  May 28 '17 at 13:49
  • Great! If this solution resolved your problem then you can accept the solution by clicking the green check mark below the voting buttons. This will help the community focus on unanswered questions on this site. – RBT May 28 '17 at 14:34