MVC3 How to disable/enable ActionLink

前端 未结 5 1539
鱼传尺愫
鱼传尺愫 2020-12-10 03:04

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 = @Mode

相关标签:
5条回答
  • 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.

    0 讨论(0)
  • 2020-12-10 03:35

    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?

    0 讨论(0)
  • 2020-12-10 03:45

    A little late to the party, but in case anyone else stumbles across this... If your project is bootstrapped, you can do this:

    @Html.ActionLink("Delete", "Delete", new { id = @Model.Id}, new { @class = "btn btn-default disabled" })
    

    or

    @{
        bool btnDisabled = // Logic here;
    }
    
    @Html.ActionLink("Delete", "Delete", new { id = @Model.Id}, new { @class = "btn btn-default " + @btnDisabled })
    
    0 讨论(0)
  • 2020-12-10 03:46

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-10 03:49

    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>
    
    0 讨论(0)
提交回复
热议问题