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?
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) %>
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.
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.
精彩评论