Search code examples
c#model-view-controllerwebgrid

How do you make an MVC Webgrid show multiple lines in a cell?


I have a function in code that generates a string A\nB\nC, when it is pulled into my Webgrid, I use a function on the Razor side to change the \n to a <br />, and I know this works because in the webpage source it shows the string on three separate lines.

@functions { public static string ReplaceLineBreaks(string s) { return s.Replace(Environment.NewLine, "@Html.Raw(<br />)"); } }

<div id="grid_MyWebGrid"> @grid.GetHtml( tableStyle : "table", alternatingRowStyle : "alternate", headerStyle : "header", columns: grid.Columns( grid.Column("Letters", format: item => @Html.Raw(ReplaceLineBreaks(Html.Encode(item.Letters)))), ) ) </div>

But when I load the page, the cell for that column shows:

ABC

Instead of:

A B C

Is there something in WebGrid that lets you tell it that that column is to be used as a multi-line cell?


Solution

  • I found something called a @helper that will you can use to design Razor inline templates. Using a @helper, I wrote a foreach statement that would create spans for each of the strings.

    @helper DisplayMultiLine(string str) { foreach(string s in str.Split(new char[] {'\n'})) { @s <br /> } }

    <div id="grid_searchentities"> @grid.GetHtml( tableStyle : "table", alternatingRowStyle : "alternate", headerStyle : "header", columns: grid.Columns( grid.Column("Letters", format:@<text>@DisplayMultiLine(@item.Letters)</text>), ) ) </div>