如何在不破坏视图的情况下使用 Html Helpers 在 ASP.NET MVC3 中禁用超链接?

Cic*_*ami 2 c# html-helper hyperlink asp.net-mvc-3

我正在使用 Razor 和 C# 开发 ASP.NET MVC3 应用程序。我想知道是否有任何方法可以“禁用”使用助手呈现的超链接,Html.ActionLink不会使用if构造破坏我的视图。至于禁用,我的意思是链接变得不可点击、变灰且没有下划线。

为了使事情清楚,我特此附上我目前用来制作技巧的原样代码。我没有禁用超链接,而是将 N/A 显示为纯文本。

视图部分:

 <td>@if(topic.EnableTopicDownloadLink)
    {
        @Html.ActionLink("Presentation", "Download", new { topicId = topic.TopicId })
    }
    else
    {
         @Html.Raw("N/A");
    }           
</td>

<td>@if (topic.EnableTopicWatchLink)
    {
        @Html.ActionLink("Video", "Play", new { topicId = topic.TopicId })
    }
    else
    {
        @Html.Raw("N/A");
    }     
</td>
Run Code Online (Sandbox Code Playgroud)

并将 ViewModel 传递给 View

public class TopicDownloadViewModel
    {
        public int TopicId { get; set; }
        public string TopicName { get; set; }
        public string TopicPresenter { get; set; }
        public string TopicStartTime { get; set; }
        public string TopicEndTime { get; set; }
        public bool EnableTopicWatchLink { get; set; }
        public bool EnableTopicDownloadLink { get; set; }

        public TopicDownloadViewModel(WebinarTopic webinarTopic)
        {
            TopicId = webinarTopic.TopicId;
            TopicName = webinarTopic.TopicName;
            TopicPresenter = webinarTopic.TopicPresenter;
            TopicStartTime = String.Format("{0:t}", webinarTopic.TopicStartTime);
            TopicEndTime = String.Format("{0:t}", webinarTopic.TopicEndTime);
            EnableTopicWatchLink = (webinarTopic.TopicVideoWatchLink != null) ? true : false;
            EnableTopicDownloadLink = (webinarTopic.TopicSlidesDownloadLink != null) ? true : false;
        }
    }
Run Code Online (Sandbox Code Playgroud)

我知道有一个禁用的 HTML 属性<a>但启用链接的唯一方法是省略该属性,我不知道如何在不使用 jQuery 的情况下执行此操作。如果可行,我的意图是不使用 jquery。

谢谢

弗朗切斯科

arc*_*hil 5

我理解正确,主要问题是您不想创建额外的 If -s。我会在你的地方做自定义助手

public static MvcHtmlString ActionLink<TModel>(this HtmlHelper<TModel> helper, string linkText, string action, object routeValues, bool disable)
    {
        if (disable)
        {
            return helper.ActionLink(linkText, action, routeValues, new { disabled = "disabled" });
        }
        return helper.ActionLink(linkText, action, routeValues);
    }
Run Code Online (Sandbox Code Playgroud)

并传递最后一个值,就像你习惯的那样,但在参数中,没有@if

    @Html.ActionLink("Presentation", "Download", topic.EnableTopicDownloadLink)
Run Code Online (Sandbox Code Playgroud)

我的代码需要修改以接受自定义 htmlattributes (topicId) 并与disabled. 为此,您可以HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);在方法主体中使用和合并禁用属性与返回值