AlexW
AlexW

Reputation: 2589

Get current action in partial view and run jQuery

I have a partial view with a menu in, depending on the current action i want to show or hide a link, my attempt at this is below

@if (ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString() == "Users")
{
    <script>
        $("#addVS").show();
    </script>
}   
    <li>@Html.ActionLink("Users", "Users", "Users")
        <ul id="addVS" style="display:none;">
            <li>@Html.ActionLink("Add New User", "AddEditRecord", "Users",new { mode = "null"}, new { @id = "openDialog" })</li>
        </ul>
    </li>

Upvotes: 0

Views: 601

Answers (2)

Jack
Jack

Reputation: 1352

Is there a reason you're using jQuery, rather than just letting the controller hide or show the <li></li>?

<li>@Html.ActionLink("Users", "Users", "Users")
    @if (ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString() == "Users")
    {
            <ul id="addVS">
                <li>@Html.ActionLink("Add New User", "AddEditRecord", "Users",new { mode = "null"}, new { @id = "openDialog" })</li>
            </ul>
    }   
</li>

This way the controller renders the menu when it builds the partial view.

If you have to use jQuery to hide or show the link, don't put the script inside the razor conditional statement. Put the script tag in the header or footer of the parent view and use jQuery to check if the condition is true and hide/show accordingly

<script type="text/javascript">

if(condition is true){
    $("#addVS").show();
}
</script>

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

You probably don't need to use any javascript but simply conditionally output the anchor on server side:

<li>
    @Html.ActionLink("Users", "Users", "Users")

    @if (ViewContext.RouteData.GetRequiredString("action") == "Users")
    {
        <ul>
            <li>
                @Html.ActionLink(
                    "Add New User", 
                    "AddEditRecord", 
                    "Users",
                    new { mode = "null" }, 
                    new { id = "openDialog" }
                )
            </li>
        </ul>
    }
</li>

Upvotes: 1

Related Questions