1

I have MVC website, and I would like to show some code snippets as text on my website. Something like this:

List<ImageInfoModel> imgList = new List<ImageInfoModel>();
string imgPath = @"~/Content/Images/ImageGallery/";
string tmbPath = @"~/Content/Images/ImageGallery/thumbnails/";

string imgFullPath = Server.MapPath(imgPath);
string tmbFullPath = Server.MapPath(tmbPath);

If I simply copy and paste this into my view with

code text

it messes things up because of @ symbol.

So my question is: How can I display C# code inside my view?

Thanks in advance.

1
  • check out @Html.Raw as a starting point. Commented Mar 25, 2015 at 5:06

3 Answers 3

2

In your View file, add a @ wherever you start razor syntax. This will escape the Razor codes and treat it like a html code.

List<imageinfomodel> imgList = new List<imageinfomodel>
();
string imgPath = @@"~/Content/Images/ImageGallery/";
string tmbPath = @@"~/Content/Images/ImageGallery/thumbnails/";

string imgFullPath = Server.MapPath(imgPath);
string tmbFullPath = Server.MapPath(tmbPath);
Sign up to request clarification or add additional context in comments.

Comments

0

If its directly from a model why not try @Html.Rawor if its in the view you could prefix the statements with @:.

1 Comment

@: doesn't stop razor statement processing. so @:@model.prop is so cool will still output the value of model.prop.
0

Use this: Code behind:

        string Sk = "List&lt;ImageInfoModel&gt; imgList = new List&lt;ImageInfoModel&gt;();<br/>";
        Sk += "string imgPath = @";
        Sk += "\"~/Content/Images/ImageGallery/\";<br/>";
        Sk += "string tmbPath = @";
        Sk += "\"~/Content/Images/ImageGallery/thumbnails/\";<br/>";
        Sk += "string imgFullPath = Server.MapPath(imgPath);<br/>string tmbFullPath = Server.MapPath(tmbPath);";
        ViewBag.Sk = Sk;

View: @Html.Raw(ViewBag.Sk)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.