开发者

ActionLink in if-statement doesn't display

I have a strange issue where an ActionLink won't display. I have this code in my view:

@if (User.IsInRole("Allow Create")) {
    Html.ActionLink("Add a new item", "Create");
}

I thought that maybe my roles and permissions weren't set up correctly, but I went through 开发者_如何转开发the debugger, and sure enough the if-statement succeeds. It reaches the code to create the action link, and there are no errors.

But when the page loads, there is no link. It's not hidden or anything either, it's not in the source at all.

Anyone know what I'm doing wrong here?


you need an extra @

@if (User.IsInRole("Allow Create")) {
    @Html.ActionLink("Add a new item", "Create");
}

As for the explanation: the @if (User.IsInRole("Allow Create")) { puts you inside a code block, and razor figures that you are just calling Html.ActionLink(..) as if you were calling a function while not bothering about the returned result. Since you actually want to output the result of the Html.ActionLink as html, you are mixing code and text for which you need the @ prefix.

Just to illustrate, the following will have the same outcome as the code above:

@if (User.IsInRole("Allow Create")) {
    var url = Html.ActionLink("Add a new item", "Create");
    @url;
}

Here is a nice Quick Reference

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜