peter
peter

Reputation: 124

How to use lambda in mvc 3 razor

I have some razor codes like this.


@{
    Layout = null;
    var Nav = ViewData["Nav"] as List<string>;
}
@{
    if(Nav!=null){
        Nav.ForEach(item =>
        {
            @<a>123@(item)</a>
        });
    }
}

but I am getting on these lines. Error is:

Server Error in '/' Application. Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS1002: ; expected

Source Error:

Line 8:          {

Line 9:              @<a>123@(item)</a>

Line 10:         });

Line 11:     }

Line 12: }

If I replace the ForEach Method with foreach block,It works good.

foreach (var item in Nav)
{
    <a>@item</a>
}

But I don't like foreach, it looks so ugly.
How can I use the ForEach Method instand of foreach block?

Upvotes: 1

Views: 1499

Answers (3)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

@if (Nav != null)
{
    Nav.ForEach(x =>
    {
        Func<object, HelperResult> res = @<a>123@(item)</a>;
        Write(res(x));
    });
}

Are you sure that this looks more readable than:

foreach (var item in Nav)
{
    <a>123@(item)</a>
}

As an alternative you could use Razor Delegated helpers.

Upvotes: 2

Paul Tyng
Paul Tyng

Reputation: 7584

Here is a good article on using templated lambda's in Razor: http://haacked.com/archive/2011/02/27/templated-razor-delegates.aspx

There are a couple problems. First you need to indicate you are writing HTML in your lamda, so you have to explicitly call Write or WriteTo on the HelperResult. Also, since { } in your lambda signify a block, you need to end all lines with a semi-colon.

Try using something like Haacked's List extension:

public static class RazorExtensions {
    public static HelperResult List<T>(this IEnumerable<T> items, 
      Func<T, HelperResult> template) {
        return new HelperResult(writer => {
            foreach (var item in items) {
                template(item).WriteTo(writer);
            }
        });
    }
}

Upvotes: 1

Chris Derry
Chris Derry

Reputation: 41

I think it is because you have put two @ symbols on the Same line try following

if(Nav!=null){
    Nav.ForEach(item =>
    {
        <a>123
         @(item)
        </a>
    });
}

Hop this helps.

Upvotes: 0

Related Questions