Bob Horn
Bob Horn

Reputation: 34297

Run Code When a Partial View is Shown

First, I'm sure I'm missing a best-practice way to navigate to and load partial views. So, if I'm going about this all the wrong way, please let me know. I have a feeling I'm making this more difficult than it needs to be.

What I'm trying to accomplish is having my web site behave like a single page app. In order to do that, I have many partial views within divs. I hide all divs but the active one. I'm not sure how to run code in a partial view only when it is shown.

Here is the div and partial view that I'm concerned with in this scenario (this is in Index.cshtml):

<div id="app">
    @Html.Partial("~/Views/PartialViews/App.cshtml")
</div>

And this is the JavaScript that shows that partial view (also in Index.cshtml):

    function showApp(id) {
        hideAll();
        $('#txtAppId').val(id);  // This is how I'm passing data to the partial view
        $('#app').show();
    }

This works well (at least as far as showing the partial view), but how can I get code in App.cshtml to run only when it is shown like this?

In App.cshtml (the partial view):

<script>
    $(function() {
        // Note: This will execute as soon as the main page is loaded. I don't want
        //       code to execute right away, but only when this view is shown.
    });

    function doSomething() {
        // Only when this view is shown do I want code to execute here.
    }
</script>

How can I have doSomething() run when the partial view is shown?

Upvotes: 0

Views: 779

Answers (1)

PSL
PSL

Reputation: 123739

Invoke the function after you show the partial view, in index.cshtml

function showApp(id) {
        hideAll();
        $('#txtAppId').val(id);  // This is how I'm passing data to the partial view
        $('#app').show();
        doSomething(); //Here invoke it.
    }

You cannot directly detect when an element changes its visibility and run some script, here you have the control of when it becomes visible so invoke the method once you make it visible.

Upvotes: 1

Related Questions