Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating strings in Razor

How would I join two strings in Razor syntax?

If I had: @Model.address and @Model.city and I wanted the out put to be address city what would I do? Is it as simple as doing @Model.address + " " + @Model.city?

like image 466
TheWebs Avatar asked Apr 19 '13 13:04

TheWebs


People also ask

How do I combine multiple strings into one?

You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

Can I concatenate strings in Python?

In Python, you can concatenate two different strings together and also the same string to itself multiple times using + and the * operator respectively.

Can you concatenate C style strings?

In C, the strcat() function is used to concatenate two strings. It concatenates one string (the source) to the end of another string (the destination). The pointer of the source string is appended to the end of the destination string, thus concatenating both strings.


1 Answers

Use the parentesis syntax of Razor:

@(Model.address + " " + Model.city) 

or

@(String.Format("{0} {1}", Model.address, Model.city)) 

Update: With C# 6 you can also use the $-Notation (officially interpolated strings):

@($"{Model.address} {Model.city}") 
like image 119
Stephen Reindl Avatar answered Sep 29 '22 18:09

Stephen Reindl