JamesStuddart
JamesStuddart

Reputation: 2611

Dynamic markup with MVC

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,

Upvotes: 0

Views: 323

Answers (3)

JamesStuddart
JamesStuddart

Reputation: 2611

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

Upvotes: 0

D&#39;Arcy Rittich
D&#39;Arcy Rittich

Reputation: 171411

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.

Upvotes: 0

djdd87
djdd87

Reputation: 68466

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>

Upvotes: 1

Related Questions