views:

28

answers:

3

Hi all,

I have markup stored in a database, which I am pulling out and placing onto a page. below is a basic sample of what I have, without any db calls for ease of example;

The controller:

ViewData["testMarkup"] = "I was here <%= DateTime.Now.Year %>";

The View:

<%= ViewData["testMarkup"] %>

now this out puts: I was here and no date, this is because it is ignoring the <%= %> part, is there anyway I can output the above said string and woudl include the year?

Many thanks,

+1  A: 

Just do the following:

ViewData["testMarkup"] = "I was here " + DateTime.Now.Year.ToString();

Or am I missing something? Code blocks, such as <%= DateTime.Now.Year %> are only valid when they are part of the markup:

<div>The year is <%= DateTime.Now.Year %></div>
GenericTypeTea
your solution would work but is not what is needed, you cant put that in the DB.
JamesStuddart
The only way you'd be able to achieve this is to use some nasty string manipulation. i.e. have placeholders within your db markup that you perform find and replaces on when rendering the view.
GenericTypeTea
A: 

The markup in the database is being treated as a string, not as code in your view language, so it is simply writing it out as text, c# and all.

Two alternate methods:

1 - Use a templating system, such as

ViewData["testMarkup"] = "I was here #YEAR#";

and have a method that replaces your tokens (e.g. #YEAR#) with their values at render time, e.g.,

<%= ReplaceTokens((string)ViewData["testMarkup"]) %>

Where ReplaceTokens looks like:

public static ReplaceTokens(string s)
{
    return s.Replace("#YEAR#", DateTime.Now.Year)
}

2 - Store your markup in a partial view, and save the name of the partial view in the database if necessary.

RedFilter
JamesStuddart
A: 

I do believe Phil Haack has the answer to my issue. http://haacked.com/archive/2009/04/22/scripted-db-views.aspx

I will have to check this out and see what happens

JamesStuddart