if 语句在视图中显示 html.actionlink

发布于 2024-10-09 07:14:53 字数 197 浏览 3 评论 0原文

我有一个显示评论列表的视图。现在,评论可以有一个与其关联的文档,因此当我显示每个评论时,我需要检查“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 技术交流群。

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

发布评论

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

评论(3

小嗲 2024-10-16 07:14:53

就我个人而言,我会在视图中将其作为 if 语句来执行,因为很清楚您的意图,但是如果您愿意,您可以添加一个扩展方法:

public static MvcHtmlString AttachedDocumentLink(this HtmlHelper helper, string text, string action, string controller, int? attachedDocumentId)
{
    return attachedDocumentId == null ? MvcHtmlString.Empty : helper.ActionLink(text, action, controller, new { id = attachedDocumentId }, null);
}

然后像平常一样在视图中调用它

<%= Html.AttachedDocumentLink("Document", "AttachedDocument", "Posts", comment.AttachedDocumentId) %>

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:

public static MvcHtmlString AttachedDocumentLink(this HtmlHelper helper, string text, string action, string controller, int? attachedDocumentId)
{
    return attachedDocumentId == null ? MvcHtmlString.Empty : helper.ActionLink(text, action, controller, new { id = attachedDocumentId }, null);
}

Then call it in your view like normal

<%= Html.AttachedDocumentLink("Document", "AttachedDocument", "Posts", comment.AttachedDocumentId) %>
凯凯我们等你回来 2024-10-16 07:14:53

戴夫是对的 - 视图中的 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.

反差帅 2024-10-16 07:14:53

如果您有一个单独的视图模型 (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.

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