使用 MVC 进行动态标记

发布于 2024-09-19 15:54:08 字数 345 浏览 2 评论 0原文

我将标记存储在数据库中,我将其取出并放置到页面上。 下面是我所拥有的基本示例,为了便于示例,没有任何数据库调用;

控制器:

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

视图:

<%= ViewData["testMarkup"] %>

现在输出:我在这里 并且没有日期,这是因为它忽略了 <%= %>部分,我是否可以输出上述字符串并包含年份?

非常感谢,

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,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

悟红尘 2024-09-26 15:54:09

只需执行以下操作:

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

或者我错过了什么?代码块,例如 <%= DateTime.Now.Year %> 仅当它们是标记的一部分时才有效:

<div>The year is <%= DateTime.Now.Year %></div>

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>
愛上了 2024-09-26 15:54:09

数据库中的标记被视为字符串,而不是视图语言中的代码,因此它只是将其写为文本、C# 等。

两种替代方法:

1 - 使用模板系统,例如

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

并有一个方法可以在渲染时用令牌(例如 #YEAR#)的值替换令牌(例如 #YEAR#),例如,

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

Where ReplaceTokens 看起来像:

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

2 - 将标记存储在分部视图中,并在必要时将分部视图的名称保存在数据库中。

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.

乖乖兔^ω^ 2024-09-26 15:54:09

我确实相信菲尔·哈克(Phil Haack)可以解决我的问题。 http://haacked.com/archive/2009/04/ 22/scripted-db-views.aspx

我必须检查一下,看看会发生什么

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文