Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested operations with Razor View Engine

I cannot figure out how to do "nested" operation in Razor. For example how to use IF inside FOREACH. VisualStudio throws compile-time error on following block, saying "Invalid expression term 'if' "

@foreach (var document in Model) {

    @if (document.Item.Count > 0) {
        <div>
            @MvcHtmlString.Create(document.Items[0].ContentPresenter)
        </div>
    }

}
like image 580
Alex Uslontsev Avatar asked Oct 05 '10 23:10

Alex Uslontsev


People also ask

How does a Razor view engine work?

Web Form Engine has the same syntax like Asp.net Web Forms uses for . aspx pages. By default, Razor Engine prevents XSS attacks(Cross-Site Scripting Attacks) means it encodes the script or html tags like <,> before rendering to view. Razor Engine is little bit slow as compared to Webform Engine.

Why we use Razor View Engine in MVC?

It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine. You can use it anywhere to generate output like HTML. It's just that ASP.NET MVC has implemented a view engine that allows us to use Razor inside of an MVC application to produce HTML.

Which type of content is observed on a razor Web page?

In a web page that uses the Razor syntax, there are two kinds of content: client content and server code. Client content is the stuff you're used to in web pages: HTML markup (elements), style information such as CSS, maybe some client script such as JavaScript, and plain text.


1 Answers

Don't you just need to drop the @ off the @if and make it:

@foreach (var document in Model) {
    if (document.Item.Count > 0) {
        <div>
            @MvcHtmlString.Create(document.Items[0].ContentPresenter)
        </div>
    }
}

Sorry I haven't worked with Razor but isn't its selling point the automatic switching back and forth between code and HTML based on context?

like image 108
Carson63000 Avatar answered Oct 05 '22 23:10

Carson63000