有没有比 <%= %> 更好、更简单的方式来提取内联文本?

发布于 2024-08-15 14:12:09 字数 384 浏览 2 评论 0原文

假设我正在 .aspx 页面(或视图,对于 MVC 人员来说)中工作,并且我有一个内联代码块:

<p>Some HTML and content</p>

<% foreach (var x in foo) { %>
   <%= x.myProperty %>
<% } %>

<p>Moar HTMLz</p>

是否有比此模型更有效、更简单的方法将文本提取到标记中?似乎有很多 <%

EDIT 我想我真正要问的是是否有更好的方法从页面上获取文本代码块,而不离开代码块,重新进入代码块,然后重新进入封闭的代码块。

Let's say I am working in a .aspx page (or View, for the MVC folk) and I have a block of inline code:

<p>Some HTML and content</p>

<% foreach (var x in foo) { %>
   <%= x.myProperty %>
<% } %>

<p>Moar HTMLz</p>

Is there a more efficient, less cumbersome way to extract text into the markup than this model? It seems like there are a lot of <%'s

EDIT I guess what I'm really asking is if there's any better way to get text on the page from a codeblock without leaving the code block, re-entering into a code block, and then reentering the enclosing codeblock.

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

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

发布评论

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

评论(2

善良天后 2024-08-22 14:12:10

为可枚举集合创建一个扩展方法:

public static void Each<T>(this IEnumerable<T> list, Action<T> fn)
{
          foreach (T item in list)
        fn(item);
}

然后执行以下操作:

foo.Each((i) => Response.Write(Html.Encode(x.MyProperty)));

public void WriteText(string coreText)
{
    Response.Write(Html.Encode(coreText));
}

或者,为了使其更容易,请使用自定义视图页面(对于 MVC)或自定义页面类(对于 Web 表单),该类具有已经为您执行此操作的方法 让它变得更加容易。扩展方法对此确实有帮助。

Create an extension method for enumerable collections:

public static void Each<T>(this IEnumerable<T> list, Action<T> fn)
{
          foreach (T item in list)
        fn(item);
}

And then do:

foo.Each((i) => Response.Write(Html.Encode(x.MyProperty)));

Or, to make it even easer, use a custom view page (for MVC) or custom page class (for Web forms) that has a method that does this already for you:

public void WriteText(string coreText)
{
    Response.Write(Html.Encode(coreText));
}

To make it even easier. Extension methods really help with that.

栀子花开つ 2024-08-22 14:12:09

如果目标严格是减少<% %>部分,您可以将其写得很长,但这很难说是一种改进:

<% foreach (var x in foo) {
       Response.Write(Html.Encode(x.MyProperty));
   } %>

如果您只想将其保留在 aspx 页面之外,则可以将其移动到控件中:

<% Html.RenderPartial("properties", foo); %>

此技术的一个优点是您可以利用不同的视图引擎(例如,NHaml)用于部分,同时仍然保持 aspx 页面(视图)的总体结构完好无损。

If the goal is strictly to have fewer <% %> sections, you can write it out the long way, but that's hardly an improvement:

<% foreach (var x in foo) {
       Response.Write(Html.Encode(x.MyProperty));
   } %>

If you just want to keep it out of the aspx page, you could move it to a control:

<% Html.RenderPartial("properties", foo); %>

One advantage of this technique is that you could utilize a different view engine (say, NHaml) for the partial while still keeping the general structure of your aspx page (view) in tact.

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