This code is copied directly from Scott Gu's blog (http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx):
Hello @name, the year is @DateTime.Now.Year
When I try this, it works:
@foreach (var post in ViewBag.Posts)
{
@post.Title<br />
}
But when I try this, the code highlighter gets the whole thing as one Razor declaration and the compiler fails:
@foreach (var post in ViewBag.Posts)
{
@post.Title, by @post.Author<br />
}
I get Compiler Error Message: CS1525: Invalid expression term ','
. Again, with just @post.Title<br />
it compiles just fine.
What am I missing here?
It is server-side markup language however it is not at all a programming language. Razor is a templating engine and ASP.NET MVC has implemented a view engine which allows us to use Razor inside of an MVC application to produce HTML. However, Razor does not have any ties with ASP.NET MVC.
Razor Engine is an advanced view engine. This is not a new language but it is a new markup syntax. The namespace for Razor Engine is System.Web.Razor. View file extension is .cshtml or .vbhtml (partial and layout view) based on language.
It’s vital to realize ASP.NET MVC uses Razor as a template engine, and that they aren’t the same thing. The good news is we can use Razor too for our bespoke needs. Using the library RazorEngine.NetCore, we can add powerful templating features to any .NET Core application.
Out of the box, Html and Url are not currently supported without specialising a custom base template. The upcoming v3 release will be accompanied by an associated RazorEngine.Web release, which will hopefully include an MVC3 compatible base template with Html and Url support.
If the content isn't obviously either language or content, you need to help it decide:
@foreach (var post in ViewBag.Posts)
{
@:@post.Title, by @post.Author<br />
}
or:
@foreach (var post in ViewBag.Posts)
{
<text>@post.Title, by @post.Author<br /></text>
}
or
@foreach (var post in ViewBag.Posts)
{
<text>
@post.Title, by @post.Author<br />
</text>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With