5

Can someone please explain how the following the following is achieved. The Telerik Grid component will generate non-encoded HTML with the following code:

@(Html.Telerik().Grid(Model)
        .Name("Grid")
        .DataKeys(keys => keys.Add(c => c.ProductID))
        .DataBinding(dataBinding => dataBinding.Server()
            .Select("ColumnSettings", "Grid")
            .Update("ColumnSettings_Save", "Grid")
            .Delete("ColumnSettings_Delete", "Grid"))
        .Columns(columns =>columns.LoadSettings((IEnumerable<GridColumnSettings>)ViewData["Columns"]))
        .Sortable()
)

Presumably this happens because the method call is wrapped in "@(....)". Whenever I try this with my own components the result is encoded Html. I know that I can use Render() to output an MvcHtmlString and then my Html is not encoded but the Telerik grid seems to achieve it without .Render().

Can anyone explain the secret to me?

tereško
  • 58,060
  • 25
  • 98
  • 150
M. Nichols
  • 51
  • 1
  • 1
    They're returning an `IHtmlString` rather than a standard `string` which MVC doesn't encode. http://geekswithblogs.net/shaunxu/archive/2010/04/10/lt-gt-htmlencode-ihtmlstring-and-mvchtmlstring.aspx – Buildstarted Jul 21 '11 at 14:35

1 Answers1

3

The @( ) syntax just allows this command to span multiple lines (otherwise a line break would be interpreted - incorrectly - as the end of the statement) and doesn't affect the encoding.

You are right - they are outputting an MvcHtmlString which avoids the automatic Razor encoding.

More specifically, all of those methods are part of a Builder object, a fluent interface which returns itself from every call. The Builder itself implements IHtmlString, so that's why the .Sortable() call or any other call in this chain will render the HTML unencoded.

Jess Chadwick
  • 2,373
  • 2
  • 21
  • 24