天道酬勤,学无止境

Use Sections in Partial Views in MVC 4.0

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.

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

评论

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 from the controller class

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

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

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);
    }
}

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.

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');
}

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"/>

This has not been possible in ASP.NET MVC 3 (See second comment in this post). Sections can only be used in (main) views, not in partial ones.

I'm currently unable to find any resources according to MVC version 4 but a short test in Visual Studio also fails for MVC 4 unless you render the whole partial view inside of the section.

Nevertheless I would not recommend to do things like this. I've been experiencing caching issues in the past with donut-caching partial views for example. Caching the partial views resulted in code not being executed and caused that neccessary javascript code has not been rendered. So I recommend to put everything you need for the partial view in the partial view itself or (what would even be better) think about a clear design and put all your javascript code in one minified javascript file that is loaded once for the whole page (and then is cached in the browser's cache).

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • 如何在MVC4的局部视图中添加脚本?(How to add a script in a partial view in MVC4?)
    问题 这是我局部视图中的代码 @model Contoso.MvcApplication.Models.Exercises.AbsoluteArithmetic @using(Html.BeginForm()) { <div> <span style="width: 110px; float:left; text-align:center; font-size:2.5em;">@Model.Number1</span> <span style="width: 110px; float:left; text-align:center; font-size:2.5em;">+</span> <span style="width: 110px; float:left; text-align:center; font-size:2.5em;">@Model.Number2</span> <span style="width: 110px; float:left; text-align:center; font-size:2.5em;">=</span> <span> @Html.EditorFor(model => model.Result) @Html.ValidationMessageFor(model => model.Result) </span> </div> }
  • MVC 4-如何将模型数据传递到局部视图?(MVC 4 - how do I pass model data to a partial view?)
    问题 我正在构建一个配置文件页面,该页面将包含与特定模型(Tenant)有关的许多部分-AboutMe,MyPreferences-诸如此类。 这些部分中的每个部分都将是部分视图,以允许使用AJAX进行部分页面更新。 当我在TenantController中单击ActionResult时,我可以创建一个强类型的视图,并且模型数据可以很好地传递给该视图。 我无法通过局部视图实现这一目标。 我创建了一个局部视图_TenantDetailsPartial : @model LetLord.Models.Tenant <div class="row-fluid"> @Html.LabelFor(x => x.UserName) // this displays UserName when not in IF @Html.DisplayFor(x => x.UserName) // this displays nothing </div> 然后,我有一个视图MyProfile ,它将呈现提到的局部视图: @model LetLord.Models.Tenant <div class="row-fluid"> <div class="span4 well-border"> @Html.Partial("~/Views/Tenants/_TenantDetailsPartial.cshtml"
  • Master-Detail Create Views with Razor, ASP.NET MVC 3 and .NET 4.0
    I'm new to .NET all together, please be patient with me if I have any silly mistakes. I'm using ASP.NET MVC 3 with .NET 4.0 I want to have a "Create" view for a model that has a child Model. This view should include the child model's partial "Create" view, I'll use the following simple example for illustration purposes: The Person model class Person { public string Name { get; set; } public Address { get; set; } } The Address model class Address { public string City { get; set; } public string Zip { get; set; } //A List for creating a <select/> item in the view //containing cities fetched from
  • 使用 Razor、ASP.NET MVC 3 和 .NET 4.0 创建主从视图(Master-Detail Create Views with Razor, ASP.NET MVC 3 and .NET 4.0)
    问题 我是 .NET 的新手,如果我有任何愚蠢的错误,请耐心等待。 我正在使用 ASP.NET MVC 3 和 .NET 4.0 我想为具有子模型的模型创建一个“创建”视图。 此视图应包括子模型的部分“创建”视图,我将使用以下简单示例进行说明: 人物模型class Person { public string Name { get; set; } public Address { get; set; } } 地址模型class Address { public string City { get; set; } public string Zip { get; set; } //A List for creating a <select/> item in the view //containing cities fetched from the database. //The initialization is done in the controller action returning //the related partial view. public IEnumerable<SelectListItem> CityDropDown { get; set; } ) } 控制器操作 class MyController : Controller { public
  • MVC 4 - how do I pass model data to a partial view?
    I'm building a profile page that will have a number of sections that relate to a particular model (Tenant) - AboutMe, MyPreferences - those kind of things. Each one of those sections is going to be a partial view, to allow for partial page updates using AJAX. When I click on an ActionResult in the TenantController I'm able to create a strongly typed view and the model data is passed to the view fine. I can't achieve this with partial views. I've created a partial view _TenantDetailsPartial: @model LetLord.Models.Tenant <div class="row-fluid"> @Html.LabelFor(x => x.UserName) // this displays
  • 在局部视图中使用截面(Use section in partial view)
    问题 在我的共享布局中,我希望有一个“脚本”部分来填充页面功能所需的所有脚本。 布局.cshtml <html> <head> <title>Test</title> <script src="@Url.Content("~/Scripts/jquery-2.0.3.js")" type="text/javascript"> </script> @RenderSection("Scripts", required: false) </head> <body> @RenderBody() </body> </html> 所以,我的视图加载了一个特定的 javascript,我希望它位于“脚本”部分,并且它正在工作。 索引.cshtml @model PlatformaPu.Areas.Inventura.Models.Home.Index @section Scripts { <script src="@Url.Content("~/Areas/Inventura/Scripts/Home/Index.js")" type="text/javascript"></script> } {CONTENT REMOVED FOR BREVITY} @section Footer { @Html.Partial("~/Views/Shared/_AppSelector.cshtml"
  • 对于数据验证,在哪里添加 Html.RenderPartialAsync("_ValidationScriptsPartial")?(For data validation, where to add Html.RenderPartialAsync("_ValidationScriptsPartial")?)
    问题 在我的ASP.NET Core 1.1.1应用程序中,模型验证不起作用。 我注意到一些默认的views (如login.cshtml , Register.cshtml通过创建的VS2017创建的应用程序时),在结尾处下面的代码。 但这些默认视图实际上是局部视图。 我的视图不是部分视图,是否也应将以下内容添加到我的views末尾? 或者我应该在不是部分视图的视图末尾添加什么: @section Scripts { @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } } 回答1 好, @section Scripts { @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } } 用于“客户端验证”(javascript)。 如果表单无效(根据模型验证),它不会让用户发送表单。 如果您打开 /Views/Shared/_Layout.cshtml,您将在其底部看到以下代码: @RenderSection("Scripts", required: false) 此代码块是来自@section Scripts的内容将被注入的地方,在这种情况下,是部分视图_ValidationScriptsPartial的内容。 根据required
  • Razor view engine - How can I add Partial Views
    I was wondering what, if it is possible, is the best way to render a partial using the new razor view engine. I understand this is something that wasn't finished completely by the time Right now I am using RenderPage to render the user control: @RenderPage("~/Views/Shared/LocaleUserControl.cshtml",ViewData.Model) The page calling RenderPage uses a layout (master) page with three sections defined: TitleContent, HeadContent and Maincontent. When I attempt to render my locale control from this page it appears that these sections are also required - they should only be required in the calling page
  • MVC3 Partial Views
    Still Learning MVC3, EF. For now I am connecting to MySql but I believe that will not be relevant. For simplicity, I decided to use one database for my test application and I have included a category to differentiate the data. For eg I have a news, events,info and pages categories. Now when it comes to listing contents in views for example at the homepage, I want to list latest 5 news items(news category), latest 5 events(events category), welcome text(info category). i have been able to create partialViews to list these at the different sections of the homepage. But I feel am doing this
  • Razor 视图引擎 - 如何添加局部视图(Razor view engine - How can I add Partial Views)
    问题 我想知道如果可能的话,使用新的 razor 视图引擎渲染部分的最佳方式是什么。 我知道这是当时还没有完全完成的事情 现在我正在使用 RenderPage 来呈现用户控件: @RenderPage("~/Views/Shared/LocaleUserControl.cshtml",ViewData.Model) 调用 RenderPage 的页面使用一个布局(母版)页面,其中定义了三个部分:TitleContent、HeadContent 和 Maincontent。 当我尝试从此页面呈现我的区域设置控件时,似乎这些部分也是必需的 - 它们应该只在调用页面中需要并且存在。 我收到以下消息,无论我是否在我的部分视图中包含这些部分(显然我不想包含这些部分,但它似乎是一个有趣的调试点......)。 以下部分已定义但尚未在布局页面“~/Views/Shared/LocaleUserControl.cshtml”上呈现: TitleContent; 头部内容; 主要内容 我的部分观点如下(改编自以下链接): @inherits System.Web.Mvc.WebViewPage<LocaleBaseModel> @using System.Web.UI; <p> @Html.LabelFor(model => Model.CountryName) <br /> @Html
  • Vs2010 MvcBuildViews Not firing
    This project in Vs2008 targeting .net 3.5 used to compile views. Vs2010 Targeting .net 4.0 the following view code is not picked up as an error, and I have not found anyway to listen to the mvcBuildview trace/debug output: <%{ %> A completely unmatched code block declaration is not being picked up, neither was a partial view inheriting from a non existent namespace/class. <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'DebugWithBuildViews|AnyCPU' "> <!--<BaseIntermediateOutputPath>bin/intermediate</BaseIntermediateOutputPath>--> <!--<MvcBuildViews Condition=" '$(Configuration)' =
  • How does MVC4 optimization allow partial view scripts?
    One problem with partial views and MVC, is that if your reusable partial view requires certain javascript, there was no way to include it and have it loaded at the bottom of the page in the scripts section. Beyond just the performance issue, it means that things necessary like jquery are not yet present and you have to use funky deferred execution of any jquery dependent code. The solution to this problem would be to allow sections in partials, such that the partial can register it's scripts to appear in the correct location of the Layout. Supposedly, MVC4's Optimization/bundling features are
  • Vs2010 MvcBuildViews 不触发(Vs2010 MvcBuildViews Not firing)
    问题 这个项目在 Vs2008 中针对 .net 3.5 用于编译视图。 Vs2010 Targeting .net 4.0 以下视图代码没有被选为错误,我还没有找到监听 mvcBuildview 跟踪/调试输出的方法: <%{ %> 没有选择完全不匹配的代码块声明,也没有从不存在的命名空间/类继承的部分视图。 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'DebugWithBuildViews|AnyCPU' "> <!--<BaseIntermediateOutputPath>bin/intermediate</BaseIntermediateOutputPath>--> <!--<MvcBuildViews Condition=" '$(Configuration)' == 'DebugWithBuildViews' ">true</MvcBuildViews>--> <EnableUpdateable>false</EnableUpdateable> <MvcBuildViews>true</MvcBuildViews> <DebugSymbols>true</DebugSymbols> <OutputPath>bin</OutputPath> <DefineConstants>DEBUG
  • 我应该将我的视图分成许多小视图还是只将它变成一个大视图?(Should I split my Views up into a lot of small Views or just make it one big View?)
    问题 我目前正在开发一个 MVC 3 Web 应用程序项目,我需要在首页上显示大量信息。 我在网页布局和设计方面相对较新,因此在如何构建此页面背后的代码方面遇到了障碍。 我的第一个想法是将页面(视图)拆分为尽可能多的页面(小视图),以便视图模型更小且更易于管理。 虽然我不确定这是否是正确的做法。 或者我应该尝试将页面的所有需求放入一个视图中,以显示我需要的所有信息? 回答1 将大视图对象拆分为较小的视图,您将获得许多好处,主要是可重用性、可测试性以及两个月后您不必(不可避免地)这样做的事实。 使用较小的视图将首先使您能够在项目的其他部分重用这些视图(应该有一个“如果需要”,但您这样做的可能性相当高)。 使用单个视图不会给您这样的灵活性。 较小的视图也更易于概念化(简洁、正确命名的视图将节省您阅读其一百行的时间)、维护(您可以隔离错误和对每个视图的功能更改而不影响其他视图)和进行测试(在时间、复杂性和依赖注入方面)。 通过使用单一的、庞大的视图(好吧,也许几分钟的开发),您不会获得任何收益,但是您在长期(和短期)期间错过的却是实质性的。 要在 MVC3 中使用几个较小的视图,您可以在主视图中使用部分视图, <div> @Html.Partial("_PartialView", new PartialViewModel) </div> 回答2 是的,即使您确定不会重用部分视图
  • 为什么使用 ASP.NET MVC 部分视图 (.ascx)(Why use ASP.NET MVC partial View (.ascx))
    问题 正如题目所说。 我为控制器方法添加视图的原因和场景是什么,我应该选中复选框“创建局部视图 (.ascx)? 回答1 两个主要原因是可重用性和可读性。 如果您计划在多个页面中包含相同的信息,请将其放在一个视图中,就像您在 WebForms 中使用 UserControls 一样。 如果您的页面会很大,那么将部分分解为视图也可能是个好主意。 它们将更小,更易于阅读和维护。 至于专门为“控制器方法”创建视图,我个人从不创建局部视图以将其直接用作控制器方法的结果。 当您意识到您可能需要开始移动一些东西时,它通常会稍后出现。 回答2 正如@Brandon 指出的,您使用 PartialViews 来实现可重用性和可读性。 以您有一个 IQueryable 联系人列表的场景为例。 您将有一个循环遍历列表的局部视图和一个呈现项目的局部视图。 当您这样做时,您可以编写代码来启用循环分部视图,以决定在有多种表示数据的方式时应由哪个分部视图呈现联系人。 如果您随后将这些部分视图放在共享文件夹中,则它们可以在整个应用程序中使用。 此外,您可以对控制器操作使用 AJAX/jQuery 调用。 然后该操作将返回一个 PartialView,然后可以显示在屏幕上。 当您不刷新整个页面时,使您的网站看起来非常漂亮。 回答3 您可以将部分页面(.ascx 文件)用于:
  • 使用Razor View Engine从局部视图ASP.NET MVC 3将内容注入特定部分(Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine)
    问题 我在_Layout.cshtml定义了此部分 @RenderSection("Scripts", false) 我可以很容易地从视图中使用它: @section Scripts { @*Stuff comes here*@ } 我正在努力的是如何从局部视图中将一些内容注入到本节中。 假设这是我的视图页面: @section Scripts { <script> //code comes here </script> } <div> poo bar poo </div> <div> @Html.Partial("_myPartial") </div> 我需要从_myPartial局部视图的“ Scripts部分中注入一些内容。 我怎样才能做到这一点? 回答1 部分无法在局部视图中使用,而这是设计使然。 您可以使用一些自定义助手来实现类似的行为,但老实说,包括必要的脚本是视图的责任,而不是部分的责任。 我建议使用主视图的@scripts部分来执行此操作,而不必担心脚本的局部问题。 回答2 这是一个很受欢迎的问题,所以我将发布解决方案。 我遇到了同样的问题,尽管它不是理想的,但我认为它实际上工作得很好,并且不会部分依赖于视图。 我的情况是,动作本身是可以访问的,但也可以嵌入到视图中-谷歌地图。 在我的_layout我有: @RenderSection("body_scripts"
  • KnockoutJS - Multiple partial views within on main view?
    I am trying to port an existing asp mvc app over to use knockoutjs (pure js/html) as I no longer really need any of the functionality within asp mvc. However one problem I can forsee is the way I am handling some of my pages. I have one page which contains about 12 partial views, each partial has its own model. Now with Knockout JS it seems like you should only really have 1 viewmodel/view per page, however the page I have contains a large amount of information, the sections would be akin to: Customer Details Customer Address Customer Recent Orders Customer Cards Customer Funds ... To make
  • 绑定数组在ASP.NET MVC中没有索引?(Binding arrays in ASP.NET MVC without index?)
    问题 我有一个看起来像这样的HTML: <input type="text" name="data[]" value="George"/> <input type="text" name="data[]" value="John"/> <input type="text" name="data[]" value="Paul"/> <input type="text" name="data[]" value="Ringo"/> 在PHP中,我可以收到如下数组: $array = $_POST['name']; // $array[0] == "George" 在ASP.NET MVC中,模型绑定器约定迫使我在HTML中放置索引,因此控制器可以接收数组。 <!-- HTML for the ASP.NET MVC Version --> <input type="text" name="data[0]" value="George"/> <input type="text" name="data[1]" value="John"/> <input type="text" name="data[2]" value="Paul"/> <input type="text" name="data[3]" value="Ringo"/> // C# Controller public
  • MVC4 优化如何允许部分视图脚本?(How does MVC4 optimization allow partial view scripts?)
    问题 部分视图和 MVC 的一个问题是,如果您的可重用部分视图需要某些 javascript,则无法将其包含并加载到页面底部的脚本部分。 除了性能问题之外,这意味着像 jquery 这样必要的东西还没有出现,你必须使用时髦的延迟执行任何 jquery 相关代码。 这个问题的解决方案是允许部分中的部分,这样部分可以注册它的脚本出现在布局的正确位置。 据说,MVC4 的优化/捆绑功能应该可以解决这个问题。 但是,当我在部分中调用 @Scripts.Render 时,它会在部分所在的任何地方包含它们。 将脚本放在页面的末尾并没有任何魔法。 在这里看到 Erik Porter 的评论:http://aspnet.uservoice.com/forums/41199-general-asp-net/suggestions/2351628-support-section-render-in-partialviews 我在其他一些地方看到人们说 MVC 4 解决了这个问题,但没有关于如何解决的例子。 如何在其他脚本之后在正文末尾包含部分所需的脚本,使用MVC4优化来解决问题? 回答1 您可以做的一件事是创建一些 HtmlHelper 扩展方法,如下所示: using System.Collections.Generic; using System.Linq; using System.Web
  • Nested layouts for MVC5
    I've seen a few posts on this topic: Razor Nested Layouts with Cascading Sections MVC 3 - Nested layouts - sections don't render in Areas And it always seems to be problematic. However they are both pretty old so wondering if things have changed. Basically I have a master layout, and 3 different body templates based on what kind of page it is. For examples sake: _Layout.cshtml <html lang="en"> <head> </head> <body style="padding: 50px 0;"> <header class="navbar navbar-default navbar-fixed-top" role="banner"> @Html.Partial("_MenuPartial") </header> <ol class="breadcrumbs"> @RenderSection(