如何在MVC视图中将C#代码显示为简单文本?

时间:2015-03-25 05:01:09

标签: c# asp.net-mvc

我有MVC网站,我想在我的网站上显示一些代码片段作为文本。像这样:

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);

如果我只是使用

代码文本

将其复制并粘贴到我的视图中,因为@符号会使事情变得混乱。

所以我的问题是:如何在我的视图中显示C#代码?

提前致谢。

3 个答案:

答案 0 :(得分:2)

在View文件中,在任何启动razor语法的位置添加@。这将逃脱Razor代码并将其视为html代码。

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);

答案 1 :(得分:0)

如果它直接来自模型,为什么不尝试@Html.Raw ,或者如果它在视图中,你可以在@: 前面添加语句。

答案 2 :(得分:0)

使用此: 代码隐藏

        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;

查看: @ Html.Raw(ViewBag.Sk)