How to concatenate two strings in image source wit

2019-07-11 20:49发布

问题:

I've defined the following variable in razor:

@{string imageRoot = "/_media/Images/";}

I'd like to use it here:

<img src="@imageRoot App1/MyImage.png"/>

The problem is the space within the string.

This will work but I'd like to keep the trailing slash in the variable instead of in the literal:

@{string imageRoot = "/_media/Images";}
<img src="@imageRoot/App1/MyImage.png"/>

回答1:

Looks a little ugly, but works:

@{string imageRoot = "/_media/Images/";}
<img src="@Html.Raw(imageRoot)App1/MyImage.png" />


回答2:

Use String.Concat to merge the two string.

@{imgRoot = string.Concat(imgRoot,"/_media/Images");}

or just normal imgRoot + = imgRoot + "/_media/Images" then set your variable as <img src='@imageRoot'/> or <img src="@{imageRoot+@"/App1/MyImage.png"}"/> Note that the @-symbol is a Verbatim string literal and will prevent the \ from being escaped should you have a character that escapes your string