开发者

Generating HTML from server-side block in ASP.NET MVC

This is a very newbie kind of ASP.NET question: I simply don't know and can't work out the correct syntax to use.

In my view I want to generate an action link if a certain condition is true on my model. I know how to generate a link using this syntax:

<%: Html.ActionLink("Do Something", "DoSomething", new { id = Model.ID }) %>

But for some reason that syntax doesn't work in this code:

<%
  if (Model.CanDoSomething)
    Html.ActionLink("Do Something", "DoSomething", new { id = Model.ID });
%>

I really am a newbie to ASP.NET, so I don't even know what the semantic name is for the different syntaxes <% and <%:; all I can tell is that <% is to void as <%: is to string. And clearly executing a line of code that just returns a string (Html.ActionLink()) is not going to have any effect. But what, pray what i开发者_StackOverflow社区s the correct method to make my page render the action link?

It's a great pity I can't Google on "<%"! Any links or explanations of this subject will also be much appreciated.


This will do the trick

<% if (Model.CanDoSomething) { %>
   <%: Html.ActionLink("Do Something", "DoSomething", new { id = Model.ID }) %>
<% } %>

<%: writes to the output buffer but encodes the string. You could also use <%= for unencoded output because ActionLink returns an encoded MvcHtmlString.

EDIT: This may also work

<%
  if (Model.CanDoSomething)
    Response.Write(Html.ActionLink("Do Something", "DoSomething", new { id = Model.ID }));
%>


<% - this by itself has no output. You would include code with no output in this block such as an if statement. If you want output - you must use it in conjunction with <%=
The difference with the : is that <%: means it will output to the response stream, not = required however the : means the output will be htmlencoded.

<%:"sometest&text" %>   //will emit "sometesttext" on the page.. htmlencoded.
<%="sometest&text" %> //will give you the same result without the '&' htmlencoded
<% SomeFunction() %> //will just run that function - there is no output
//you want
<%if (Model.CanDoSomething){%>
    <%:Html.ActionLink("Do Something", "DoSomething", new { id = Model.ID })%>
<%}%>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜