首先,我确定我错过了导航和加载部分视图的最佳实践方法。所以,如果我要以错误的方式处理这一切,请告诉我。我有一种感觉,我让这变得比它需要的更困难。
我想要完成的是让我的网站表现得像一个单页应用程序。为了做到这一点,我在 div 中有很多部分视图。我隐藏了除活动的所有 div 之外的所有 div。我不确定如何仅在显示部分视图时才在部分视图中运行代码。
这是我在这种情况下关心的 div 和部分视图(在 Index.cshtml 中):
<div id="app">
    @Html.Partial("~/Views/PartialViews/App.cshtml")
</div>
这是显示部分视图的 JavaScript(也在 Index.cshtml 中):
    function showApp(id) {
        hideAll();
        $('#txtAppId').val(id);  // This is how I'm passing data to the partial view
        $('#app').show();
    }
这很好用(至少就显示部分视图而言),但是我怎样才能让 App.cshtml 中的代码仅在它显示为这样时才运行?
在 App.cshtml(部分视图)中:
<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>
doSomething()显示局部视图时如何运行?