I have the following razor template html, although I can't figure out how to include a comma to separate the names within the markup!? When trying the following code I get ; expected
as a compiler error!. I'll also need to remove the last comma as well.
@foreach (People person in Model.People) { person.Name, }
I want: Ted, James, Jenny, Tom
Razor syntax is a simple programming syntax for embedding server-based code in a web page. In a web page that uses the Razor syntax, there are two kinds of content: client content and server code.
The Razor syntax consists of Razor markup, C#, and HTML.
Following are the rules for main Razor Syntax: Razor code blocks are enclosed in @{ … } Inline expressions (variables and functions) start with @ Code statements end with a semicolon.
Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.
What about string.Join instead of foreach
(it even solves the comma after the last item problem):
@String.Join(", ", Model.People.Select(p => p.Name).ToArray())
You can use <text></text>
to include literal content in a Razor template. To omit the last comma, I would use a for
loop rather than foreach
.
@{ var peopleList = Model.People.ToList(); for( int i = 0; i < peopleList.Count; i++ ) { @peopleList[i].Name if( i < peopleList[i].Count - 1 ) { <text>,</text> } } }
As @nemesv points out, if all you are doing is creating and displaying a delimited string, string.Join()
is a cleaner way to accomplish this. If you are building more complex markup, you will probably need to use a loop.
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