有没有比 <%= %> 更好、更简单的方式来提取内联文本?
假设我正在 .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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为可枚举集合创建一个扩展方法:
然后执行以下操作:
:
或者,为了使其更容易,请使用自定义视图页面(对于 MVC)或自定义页面类(对于 Web 表单),该类具有已经为您执行此操作的方法 让它变得更加容易。扩展方法对此确实有帮助。
Create an extension method for enumerable collections:
And then do:
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:
To make it even easier. Extension methods really help with that.
如果目标严格是减少<% %>部分,您可以将其写得很长,但这很难说是一种改进:
如果您只想将其保留在 aspx 页面之外,则可以将其移动到控件中:
此技术的一个优点是您可以利用不同的视图引擎(例如,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:
If you just want to keep it out of the aspx page, you could move it to a control:
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.