Savage
Savage

Reputation: 2349

Wrap code in MVC Razor

For long lines of C# code in a ASP.NET MVC Razor view, how can you wrap the code onto the next line? If I add a carriage return, it renders the code as HTML.

Edit: Here's an example of the code I would like to wrap. In the last line, the added method calls start to run off the screen and I'd like to carry something like .WithAjax(true) to the next line.

@Html.Grid(stuff).Columns(columns =>
{
    //stuff
}).Sortable().Filterable().WithMultipleFilters().WithPaging(WebSettings.DefaultPageSize)
  .WithAjax(true).Exportable(true)

Upvotes: 1

Views: 949

Answers (2)

Salah Akbari
Salah Akbari

Reputation: 39946

You can use @() like this:

@(Html.Grid(stuff).Columns(columns =>
{
//stuff
}).Sortable().Filterable().WithMultipleFilters()
  .WithPaging(WebSettings.DefaultPageSize)
  .WithAjax(true).Exportable(true))

This is called Explicit Expression.

Upvotes: 1

Georg Patscheider
Georg Patscheider

Reputation: 9463

You can enclose a "Razor code block" using the @{ } syntax. The contents will not be rendered, but variables declared inside are accessible by the rest of the page.

@{
    string longMessage = "Lorem ipsum dolor sit amet, consectetur " +
        /* these linebreaks will not be part of the string variable */ +
        "adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.";
} 

@* Now render the string variable declared in the code block *@
<p>@longMessage</p>

See Razor syntax for ASP.NET Core.

Edit

For your concrete code:

 @{
    // assign the IHtmlString created by the HTML Helper to a variable
    var grid = Html.Grid(stuff).Columns(columns =>
        {
          //stuff
        }).Sortable().Filterable().WithMultipleFilters()
        .WithPaging(WebSettings.DefaultPageSize)
        .WithAjax(true).Exportable(true));
 }

@* now render the variable content *@
@grid

Upvotes: 2

Related Questions