Search code examples
c#asp.net-mvcwebgrid

How display two columns in Mvc WebGrid with single object


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)));
}

Solution

  • 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