开发者

How can I not render a button in my view if a given property off my model has no value?

I'm new to web development. In my view, I want to conditionally show a button if Model.TemplateLocation (which is a string) is not null or empty. Below is the code that is rendering the button currently:

    <div class="WPButton MyButton">
  <%=Html.ActionLink(Model.TemplateLinkName, "DownloadTemplate", "ExternalD开发者_开发问答ata", new ArgsDownloadTemplate { Path = Model.TemplateLocation, FileName = Model.TemplateFileNameForDownload }, new{})%>
</div>

Can I wrap some C# code in the <% %>'s to test for Model.TemplateLocations value before I render that? I was told to look into @style = "display:none" somehow. Could that be what I need?


You can add control statements in code blocks to conditionally output HTML.

<% if (Model.SomeCondition) { %>
   <div>
     <ul>
      <%=Html.ActionLink(Model.TemplateLinkName, "DownloadTemplate", "ExternalData", new ArgsDownloadTemplate { Path = Model.TemplateLocation, FileName = Model.TemplateFileNameForDownload }, new{})%>
     </ul>
   </div>
<% } %>

Incidentally, the <%= %> version of the tag is simply a shortcut for a code call to Response.Write(). So this will accomplish the exact same thing:

<% if (Model.SomeCondition) { 
   Response.Write("<div><ul>");
   Response.Write (Html.ActionLink(Model.TemplateLinkName, "DownloadTemplate", "ExternalData", new ArgsDownloadTemplate { Path = Model.TemplateLocation, FileName = Model.TemplateFileNameForDownload }, new{}));
   Response.Write("</ul></div>");
} %>

Much debate exists as to the correctness of either method. Many people hate the number of ASP tags they have to use to do the first way, many people feel the second way is incorrect for whatever reason. I find I use both when it offers simpler reading of the code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜