Reputation: 455
I'm trying to render a string that is stored in my database as if it were from a CSHTML file. Here is a sample string that I'd like to render:
<footer>
<div class="content-wrapper">
<div class="float-left">
<p>© @DateTime.Now.Year - My ASP.NET MVC Application</p>
</div>
</div>
</footer>
Notice that "@DateTime.Now.Year"? Well, if this were stored in a database, how would I render this into a view and have that part of it actually render as 2014 (or whatever year it is that you're reading this)?
Upvotes: 1
Views: 2819
Reputation: 3956
You can use RazorEngine (NuGet package "RazorEngine") for this.
Package Manager Console:
PM> install-package razorengine
In your code:
string template = GetYourTemplateFromDatabase();
string content = RazorEngine.Razor.Parse(template, null);
If you want to add this output to your actual view you would have to add it as an IHtmlString
or use @Html.Raw(ViewBag.Content)
:
Controller code (for IHtmlString
):
ViewBag.DatabaseCode = MvcHtmlString.Create(content);
View code:
<div>
@ViewBag.DatabaseCode
</div>
Upvotes: 5
Reputation: 6832
If I understand correctly, you're storing that whole HTML snippet in the database? You could do a simple String.Replace
on the string you get from the database.
<footer>
<div class="content-wrapper">
<div class="float-left">
<p>© {{YEAR}} - My ASP.NET MVC Application</p>
</div>
</div>
</footer>
And then in the view :
@Html.Raw(Model.Footer.Replace("{{YEAR}}", DateTime.Now.Year))
Upvotes: 0
Reputation: 1462
you need define a model in razor this is a good example http://weblogs.asp.net/scottgu/asp-net-mvc-3-new-model-directive-support-in-razor
Upvotes: 0