MVC Razor View escape character

The Problem

You want to use your model or some code to append a variable inline with a string.
Assume you want to create a URL with a dynamic element like:
[csharp]
http://appserver-dev.domain.com
[/csharp]
where -dev will be an appsetting accessed in razor from @Settings.Default.URLSuffix

When you add the @Settings value in like so;
[csharp]
http://appserver@Settings.Default.URLSuffix.domain.com
[/csharp]
it treats the @Settings.Default.URLSuffix as a text string, outputting “http://appserver@Settings.Default.URLSuffix.domain.com” not “http://appserver-dev.domain.com” as you were hoping. What is the escape character?

The Solution

@@ is the escape sequence.. so that should be easy..

[csharp]
http://appserver@@Settings.Default.URLSuffix.domain.com
[/csharp]
The problem now is it treats the .domain.com as part of the code and is not happy because a string object does not have .domain.com methods.

[csharp]
http://appserver@@Settings.Default.URLSuffix;.domain.com
[/csharp]

Add a semi-colon to end the code and that is the problem solved.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.