if 语句在视图中显示 html.actionlink
我有一个显示评论列表的视图。现在,评论可以有一个与其关联的文档,因此当我显示每个评论时,我需要检查“AttachedDocumentID”是否有值,如果有,则显示一个 HTML.ActionLink 。
不确定最好的方法来避免在视图中出现 if 语句(我认为这是不好的形式),并且我真的不想在帮助器中生成任何 html 代码。
我还有什么其他选择?
I have a view that displays a list of comments. Now a comment can have a document associated to it so as I am displaying each comment I need to check whether or not "AttachedDocumentID" has a value and if so display a HTML.ActionLink to it.
Not sure on the best way to do this to avoid having an if statement in the view (which I'm led to believe is bad form) and I didn't really want to have any html code generated in the helper.
What other options do I have?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
就我个人而言,我会在视图中将其作为 if 语句来执行,因为很清楚您的意图,但是如果您愿意,您可以添加一个扩展方法:
然后像平常一样在视图中调用它
Personally I'd do it as an if statement in the view as it's clear what you're intending, but you could add an extension method if you wanted:
Then call it in your view like normal
戴夫是对的 - 视图中的 if 语句没有任何问题。循环也可以。要避免的事情是让视图执行任何类型的查询、计算或模型修改。
dave is right - there's nothing wrong with if statements in a view. loops are also ok. the things to avoid are having the view do any kind of queries or calculations or model modifications.
如果您有一个单独的视图模型 (ViewModel),请将此类逻辑移至那里。这样,属于视图的逻辑就保留在一个地方。我更喜欢仅将 HtmlHelpers 用于跨视图的通用可重用案例。
If you have a separate model for view (ViewModel), move this kind of logic there. That way logic belongs to the view stays in one place. I prefer using HtmlHelpers only for generic reusuable cases across views.