开发者

Dynamic markup with MVC

开发者 https://www.devze.com 2023-01-16 10:38 出处:网络
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;

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 stri开发者_StackOverflow中文版ng and woudl include the year?

Many thanks,


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>


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消