MVC3 How to disable/enable ActionLink

2020-02-05 07:05发布

问题:

I have if condition and I want to disable or enable my actionLink button.

How would I do it?

@Html.ActionLink("Delete", "Delete", new { id = @Model.Id})

Thanks,

回答1:

If you know on the server side that the link is not available then just render a message that the action is not available:

@if(condition)
{
   @Html.ActionLink("Delete", "Delete", new { id = @Model.Id})
}
else
{
   <text>Action is not available</text>
}

Otherwise you can only disable a link with

  • CSS: Disable link using css
  • JS: How to enable or disable an anchor using jQuery?

To make it work cross-browser: Should the HTML Anchor Tag Honor the Disabled Attribute?



回答2:

To disable a "a" tag you can do:

@Html.ActionLink("Delete", "Delete", new { id = @Model.Id}, new { onclick = "javascript:return false;" })

Or you can use JQuery:

@Html.ActionLink("Delete", "Delete", new { id = @Model.Id}, new { class = "linkdisabled" })

CSS:

.linkdisabled{
   cursor:text;
}

JQuery:

$function(){
    $(".linkdisabled").click(function(){
        return false;
    }
}


回答3:

Maybe you can create your own UI of type MvcHtmlString

public static MvcHtmlString MyActionLink(this HtmlHelper helper, bool isClickable, string altText, RouteValueDictionary routeValues, object htmlAttributes = null) 
{
    // some logic with isClickale parameter here
    if(isClickable == false)
    {}

    return new MvcHtmlString(helper.ToHtmlString());
}

and use it in your View

@Html.MyActionLink( // some parameters here )

But I have never try it. Try find something about MvcHtmlString on Google.



回答4:

Someone might find this useful, I once solved a similar problem by turning @Html.ActionLink into an input <input type="submit" id = "submit" /> and then you make it work as a link using javascript:

<script>
    $(document).ready(function () {
        $('#submit').click(function () {
            if(condition){
               //sth (not working as a link)
            }
            else
            {
                window.location.href = "/home/thanks"; //working as a link
            }
        })
</script>