Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple razor templating syntax to include a comma to separate the names

Tags:

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

like image 500
James Radford Avatar asked Mar 29 '12 08:03

James Radford


People also ask

What is the syntax of Razor?

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.

Which of the following are examples of Razor syntax?

The Razor syntax consists of Razor markup, C#, and HTML.

What are the main Razor syntax rules?

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.

What is Razor syntax in MVC?

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.


2 Answers

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()) 
like image 81
nemesv Avatar answered Sep 23 '22 10:09

nemesv


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.

like image 34
Tim M. Avatar answered Sep 21 '22 10:09

Tim M.