使用在局部视图节在MVC 4.0视图、局部、MVC

2023-09-04 09:54:00 作者:有什么会う永垂不朽

我想包括脚本在我的部分观点时,我有我需要初始化jQuery用户界面上的特定元素的情况下。这真的是属于同部分,而不是包含页面或布局。

I want to include scripts in my partial views when I have cases where I need to initialize jQuery ui on specific elements. It really belongs with the partial and not the containing page or the layout.

据说有办法做到这一点在MVC 4,但我似乎无法找到它的任何信息。

Supposedly there's a way to do it in MVC 4, but I can't seem to find any info on it.

推荐答案

我也有过类似的问题。希望这可以帮助。 我们希望有一个包含一个显示一些数据,另一部分当我们点击我们的网页链接,应该动态地改变公共首部的图。 (类似一个选项卡) 因为我们不想重装标题部分多次,我们决定有一个容器视图和一个占位符的div将用于动态加载的局部视图,当我们点击一​​个AJAX链接。 然而,得到了加载到占位部分观点有大量的JavaScript code,我们不能包括所有的,使用了不同的局部视图成一个单一的JavaScript文件中的code和从容器视图是指它因为有一些冲突的功能。 引入命名空间来解决这个问题还没有很有效的方法,因为所有的JavaScript逻辑仍然会被加载不必要的。 做了一些谷歌搜索使我认识到,在一个局部视图有一个脚本部分是行不通的。我试着用@RenderSection(partialScripts,必需:false)来定义,我认为一款失败的RenderSection仅适用于布局视图。 以下是我走上解决这个问题的办法。 即在布局视图定义的脚本部分可以包含任何有效的标记。所以我决定用一个div,这将帮我把我的容器视图的脚本的一节内动态加载脚本。操作环节的onSuccess事件处理程序来实现动态地连接脚本。 这里是code我的容器视图。

I also had a similar issue. Hope this helps. We wanted to have a view that contains a common header section that displays some data and another section that should dynamically change when we click on a link in our page. (something similar to a tab) Since we didn't want to reload the header section multiple times, we decided to have a container view and a place holder div that will be used to load a partial view dynamically when we click on a ajax link. However, partial views that got loaded into the place holder had lot of javascript code and we couldn't include all the code that were used by different partial views into a single javascript file and refer it from the container view as there were some conflicting functions. Introducing namespaces to fix that issue also wasn't very efficient approach as all the javascript logic would still have been loaded unnecessarily. Doing a bit of googling made me realize that having a script section in a partial view is not going to work. I tried to define a section in my view using @RenderSection("partialScripts", required: false) unsuccessfully as RenderSection only works in a layout view. Following is the approach i took to overcome this issue. scripts section that is defined in the layout view can contain any valid markup. so i decided to have a div that will help me to load scripts dynamically inside the scripts section of my container view. OnSuccess event handler of the action link was used to attach the scripts dynamically. Here is the code for my container view.

<ul>
    <li>
        @Ajax.ActionLink("Partial One", "PartialOne", ajaxOptions: new AjaxOptions
                     {
                         HttpMethod = "Get",
                         InsertionMode = InsertionMode.Replace,
                         UpdateTargetId = "container",
                         OnSuccess = "loadScriptsDynamically('PartialOne')"
                     })
    </li>
    <li>
        @Ajax.ActionLink("Partial Two", "PartialTwo", ajaxOptions: new AjaxOptions
                     {
                         HttpMethod = "Get",
                         InsertionMode = InsertionMode.Replace,
                         UpdateTargetId = "container",
                         OnSuccess = "loadScriptsDynamically('PartialTwo')"
                     })
    </li>
</ul>

<div id="container">
</div>

@section scripts
{
    <script src="@Url.Content("~/Scripts/app/Container.js")"></script>
    <div id="dynamicScripts"
         data-partial-one="@Url.Content("~/Scripts/App/PartialOne.js")"
         data-partial-two="@Url.Content("~/Scripts/App/PartialTwo.js")">
    </div>
}

从控制器类code

Code from the controller class

    public PartialViewResult PartialOne()
    {
        return PartialView("_PartialOne");
    }

    public PartialViewResult PartialTwo()
    {
        return PartialView("_PartialTwo");
    }

Container.js文件包含将动态加载必要的脚本不同的局部视图的逻辑。

Container.js file contains the logic that will dynamically load the necessary scripts for different partial views.

function loadScriptsDynamically(name) {
    var script = document.createElement('script');
    var dynamicScriptsDiv = document.getElementById('dynamicScripts');
    var dynamicScriptDivJQuery = $('#dynamicScripts');
    dynamicScriptDivJQuery.empty();
    if (name === 'PartialOne') {
        script.src = dynamicScriptDivJQuery.data('partial-one');
        dynamicScriptsDiv.appendChild(script);
    } else if (name === 'PartialTwo'){
        script.src = dynamicScriptDivJQuery.data('partial-two');
        dynamicScriptsDiv.appendChild(script);
    }
}

我们不能使用jQuery追加一个脚本元素,一个div由于一些限制。但是,我们可以使用一些老式的JavaScript code创建一个脚本元素,并将其添加到dynamicScriptsDiv。请注意,我访问I $ P $使用一些数据 - 属性作为我们MVC应用程序运行在IIS服务器和我们没有要到c他们难以$ C $ pviously连接到dynamicScriptsDivusing脚本路径。

We can't use jQuery to append a script element to a div due to some restrictions. But we can use some old fashioned javascript code to create a script element and append it to dynamicScriptsDiv. Please note that i am accessing the script paths i previously attached to dynamicScriptsDivusing using some data- attributes as our MVC app runs in IIS server and we didnt want to hard code them.

附加到事件之后脚本动态加载的是我们的下一个挑战。通过使用即时调用函数我能注册所有的事件绑定code和任何初始化逻辑,我必须执行以下使用code。

Attaching to events after the script is dynamically loaded was our next challenge. By using an immediate invocation function i was able to register all my event binding code and any initialization logic i have to perform using following code.

(function initPartialOne() {
    $('#myButton').click(function() {
        setLabelText();
    });
})();

function setLabelText() {
    $('#myLabel').text('One was clicked');
}

和最后的code为我的部分景色之一。

And finally the code for one of my partial views.

<label id="myLabel">[Message]</label>
<input type="button" id="myButton" value="Click me partial one"/>