vistas vista ventana una parciales parcial pagina net mvc multiples modelos modal misma llamar desde cargar bootstrap asp asp.net asp.net-mvc asp.net-mvc-3 razor partial-views

asp.net - ventana - vista parcial en modal mvc



Inyectar contenido en secciones específicas desde una vista parcial ASP.NET MVC 3 con Razor View Engine (22)

Tengo esta sección definida en mi _Layout.cshtml

@RenderSection("Scripts", false)

Puedo usarlo fácilmente desde una vista:

@section Scripts { @*Stuff comes here*@ }

Con lo que estoy luchando es cómo obtener contenido inyectado dentro de esta sección desde una vista parcial.

Supongamos que esta es mi página de vista:

@section Scripts { <script> //code comes here </script> } <div> poo bar poo </div> <div> @Html.Partial("_myPartial") </div>

Necesito inyectar algo de contenido dentro de la sección de _myPartial la vista parcial de _myPartial .

¿Cómo puedo hacer esto?


A partir de las soluciones en este hilo , se me ocurrió la siguiente solución probablemente demasiado complicada que le permite retrasar el procesamiento de cualquier html (secuencias de comandos también) dentro de un bloque de uso.

USO

Crear la "sección"

  1. Escenario típico: en una vista parcial, solo incluya el bloque una vez, sin importar cuántas veces se repita la vista parcial en la página:

    @using (Html.Delayed(isOnlyOne: "some unique name for this section")) { <script> someInlineScript(); </script> }

  2. En una vista parcial, incluya el bloque para cada vez que se use el parcial:

    @using (Html.Delayed()) { <b>show me multiple times, @Model.Whatever</b> }

  3. En una vista parcial, solo incluya el bloque una vez, no importa cuántas veces se repita el parcial, sino que más tarde, conviértalo específicamente por su nombre when-i-call-you :

    @using (Html.Delayed("when-i-call-you", isOnlyOne: "different unique name")) { <b>show me once by name</b> <span>@Model.First().Value</span> }

Renderizar las "secciones"

(es decir, mostrar la sección retrasada en una vista principal)

@Html.RenderDelayed(); // writes unnamed sections (#1 and #2, excluding #3) @Html.RenderDelayed("when-i-call-you", false); // writes the specified block, and ignore the `isOnlyOne` setting so we can dump it again @Html.RenderDelayed("when-i-call-you"); // render the specified block by name @Html.RenderDelayed("when-i-call-you"); // since it was "popped" in the last call, won''t render anything due to `isOnlyOne` provided in `Html.Delayed`

CÓDIGO

public static class HtmlRenderExtensions { /// <summary> /// Delegate script/resource/etc injection until the end of the page /// <para>@via https://.com/a/14127332/1037948 and http://jadnb.wordpress.com/2011/02/16/rendering-scripts-from-partial-views-at-the-end-in-mvc/ </para> /// </summary> private class DelayedInjectionBlock : IDisposable { /// <summary> /// Unique internal storage key /// </summary> private const string CACHE_KEY = "DCCF8C78-2E36-4567-B0CF-FE052ACCE309"; // "DelayedInjectionBlocks"; /// <summary> /// Internal storage identifier for remembering unique/isOnlyOne items /// </summary> private const string UNIQUE_IDENTIFIER_KEY = CACHE_KEY; /// <summary> /// What to use as internal storage identifier if no identifier provided (since we can''t use null as key) /// </summary> private const string EMPTY_IDENTIFIER = ""; /// <summary> /// Retrieve a context-aware list of cached output delegates from the given helper; uses the helper''s context rather than singleton HttpContext.Current.Items /// </summary> /// <param name="helper">the helper from which we use the context</param> /// <param name="identifier">optional unique sub-identifier for a given injection block</param> /// <returns>list of delayed-execution callbacks to render internal content</returns> public static Queue<string> GetQueue(HtmlHelper helper, string identifier = null) { return _GetOrSet(helper, new Queue<string>(), identifier ?? EMPTY_IDENTIFIER); } /// <summary> /// Retrieve a context-aware list of cached output delegates from the given helper; uses the helper''s context rather than singleton HttpContext.Current.Items /// </summary> /// <param name="helper">the helper from which we use the context</param> /// <param name="defaultValue">the default value to return if the cached item isn''t found or isn''t the expected type; can also be used to set with an arbitrary value</param> /// <param name="identifier">optional unique sub-identifier for a given injection block</param> /// <returns>list of delayed-execution callbacks to render internal content</returns> private static T _GetOrSet<T>(HtmlHelper helper, T defaultValue, string identifier = EMPTY_IDENTIFIER) where T : class { var storage = GetStorage(helper); // return the stored item, or set it if it does not exist return (T) (storage.ContainsKey(identifier) ? storage[identifier] : (storage[identifier] = defaultValue)); } /// <summary> /// Get the storage, but if it doesn''t exist or isn''t the expected type, then create a new "bucket" /// </summary> /// <param name="helper"></param> /// <returns></returns> public static Dictionary<string, object> GetStorage(HtmlHelper helper) { var storage = helper.ViewContext.HttpContext.Items[CACHE_KEY] as Dictionary<string, object>; if (storage == null) helper.ViewContext.HttpContext.Items[CACHE_KEY] = (storage = new Dictionary<string, object>()); return storage; } private readonly HtmlHelper helper; private readonly string identifier; private readonly string isOnlyOne; /// <summary> /// Create a new using block from the given helper (used for trapping appropriate context) /// </summary> /// <param name="helper">the helper from which we use the context</param> /// <param name="identifier">optional unique identifier to specify one or many injection blocks</param> /// <param name="isOnlyOne">extra identifier used to ensure that this item is only added once; if provided, content should only appear once in the page (i.e. only the first block called for this identifier is used)</param> public DelayedInjectionBlock(HtmlHelper helper, string identifier = null, string isOnlyOne = null) { this.helper = helper; // start a new writing context ((WebViewPage)this.helper.ViewDataContainer).OutputStack.Push(new StringWriter()); this.identifier = identifier ?? EMPTY_IDENTIFIER; this.isOnlyOne = isOnlyOne; } /// <summary> /// Append the internal content to the context''s cached list of output delegates /// </summary> public void Dispose() { // render the internal content of the injection block helper // make sure to pop from the stack rather than just render from the Writer // so it will remove it from regular rendering var content = ((WebViewPage)this.helper.ViewDataContainer).OutputStack; var renderedContent = content.Count == 0 ? string.Empty : content.Pop().ToString(); // if we only want one, remove the existing var queue = GetQueue(this.helper, this.identifier); // get the index of the existing item from the alternate storage var existingIdentifiers = _GetOrSet(this.helper, new Dictionary<string, int>(), UNIQUE_IDENTIFIER_KEY); // only save the result if this isn''t meant to be unique, or // if it''s supposed to be unique and we haven''t encountered this identifier before if( null == this.isOnlyOne || !existingIdentifiers.ContainsKey(this.isOnlyOne) ) { // remove the new writing context we created for this block // and save the output to the queue for later queue.Enqueue(renderedContent); // only remember this if supposed to if(null != this.isOnlyOne) existingIdentifiers[this.isOnlyOne] = queue.Count; // save the index, so we could remove it directly (if we want to use the last instance of the block rather than the first) } } } /// <summary> /// <para>Start a delayed-execution block of output -- this will be rendered/printed on the next call to <see cref="RenderDelayed"/>.</para> /// <para> /// <example> /// Print once in "default block" (usually rendered at end via <code>@Html.RenderDelayed()</code>). Code: /// <code> /// @using (Html.Delayed()) { /// <b>show at later</b> /// <span>@Model.Name</span> /// etc /// } /// </code> /// </example> /// </para> /// <para> /// <example> /// Print once (i.e. if within a looped partial), using identified block via <code>@Html.RenderDelayed("one-time")</code>. Code: /// <code> /// @using (Html.Delayed("one-time", isOnlyOne: "one-time")) { /// <b>show me once</b> /// <span>@Model.First().Value</span> /// } /// </code> /// </example> /// </para> /// </summary> /// <param name="helper">the helper from which we use the context</param> /// <param name="injectionBlockId">optional unique identifier to specify one or many injection blocks</param> /// <param name="isOnlyOne">extra identifier used to ensure that this item is only added once; if provided, content should only appear once in the page (i.e. only the first block called for this identifier is used)</param> /// <returns>using block to wrap delayed output</returns> public static IDisposable Delayed(this HtmlHelper helper, string injectionBlockId = null, string isOnlyOne = null) { return new DelayedInjectionBlock(helper, injectionBlockId, isOnlyOne); } /// <summary> /// Render all queued output blocks injected via <see cref="Delayed"/>. /// <para> /// <example> /// Print all delayed blocks using default identifier (i.e. not provided) /// <code> /// @using (Html.Delayed()) { /// <b>show me later</b> /// <span>@Model.Name</span> /// etc /// } /// </code> /// -- then later -- /// <code> /// @using (Html.Delayed()) { /// <b>more for later</b> /// etc /// } /// </code> /// -- then later -- /// <code> /// @Html.RenderDelayed() // will print both delayed blocks /// </code> /// </example> /// </para> /// <para> /// <example> /// Allow multiple repetitions of rendered blocks, using same <code>@Html.Delayed()...</code> as before. Code: /// <code> /// @Html.RenderDelayed(removeAfterRendering: false); /* will print */ /// @Html.RenderDelayed() /* will print again because not removed before */ /// </code> /// </example> /// </para> /// </summary> /// <param name="helper">the helper from which we use the context</param> /// <param name="injectionBlockId">optional unique identifier to specify one or many injection blocks</param> /// <param name="removeAfterRendering">only render this once</param> /// <returns>rendered output content</returns> public static MvcHtmlString RenderDelayed(this HtmlHelper helper, string injectionBlockId = null, bool removeAfterRendering = true) { var stack = DelayedInjectionBlock.GetQueue(helper, injectionBlockId); if( removeAfterRendering ) { var sb = new StringBuilder( #if DEBUG string.Format("<!-- delayed-block: {0} -->", injectionBlockId) #endif ); // .count faster than .any while (stack.Count > 0) { sb.AppendLine(stack.Dequeue()); } return MvcHtmlString.Create(sb.ToString()); } return MvcHtmlString.Create( #if DEBUG string.Format("<!-- delayed-block: {0} -->", injectionBlockId) + #endif string.Join(Environment.NewLine, stack)); } }


Acabo de agregar este código en mi vista parcial y resolví el problema, aunque no está muy limpio, funciona. Debe asegurarse de los identificadores de los objetos que está representando.

$ (documento) .ready (función () {$ ("# Profile_ProfileID"). selectmenu ({icons: {button: ''ui-icon-circle-arrow-s''}}); $ ("# TitleID_FK"). selectmenu ({icons: {button: ''ui-icon-circle-arrow-s''}}); $ ("# CityID_FK"). selectmenu ({icons: {button: ''ui-icon-circle-arrow-s'' }}); $ ("# GenderID_FK"). Selectmenu ({icons: {button: ''ui-icon-circle-arrow-s''}}); $ ("# PackageID_FK"). Selectmenu ({icons: {button : ''ui-icon-circle-arrow-s''}});});

Bueno, supongo que los otros carteles te han proporcionado un medio para incluir directamente una @sección dentro de tu parcial (mediante el uso de terceros ayudantes html).

Pero, creo que, si su script está estrechamente unido a su parcial, simplemente coloque su javascript directamente dentro de una etiqueta en línea <script> dentro de su parcial y termine con él (tenga cuidado con la duplicación de scripts si tiene la intención de usar el parcial más de una vez en una sola vista);


El objetivo del OP es que quiere definir los guiones en línea en su Vista parcial, que asumo que este guión es específico solo para esa Vista parcial, y que ese bloque esté incluido en su sección de guiones.

Entiendo que él quiere que esa Vista Parcial sea autosuficiente. La idea es similar a los componentes cuando se usa Angular.

Mi manera sería simplemente mantener los scripts dentro de la Vista Parcial tal como están. Ahora el problema con eso es cuando se llama Vista parcial, puede ejecutar el script allí antes que todos los demás scripts (que normalmente se agregan al final de la página de diseño). En ese caso, solo tiene que esperar la secuencia de comandos de Vista parcial para las otras secuencias de comandos. Hay varias formas de hacerlo. El más simple, que he usado antes, es usar un evento en el body .

En mi diseño, tendría algo en la parte inferior como esto:

// global scripts <script src="js/jquery.min.js"></script> // view scripts @RenderSection("scripts", false) // then finally trigger partial view scripts <script> (function(){ document.querySelector(''body'').dispatchEvent(new Event(''scriptsLoaded'')); })(); </script>

Luego en mi Vista Parcial (en la parte inferior):

<script> (function(){ document.querySelector(''body'').addEventListener(''scriptsLoaded'', function() { // .. do your thing here }); })(); </script>

Otra solución es usar una pila para empujar todos sus scripts y llamar a cada uno al final. Otra solución, como ya se mencionó, es el patrón RequireJS / AMD, que también funciona muy bien.


Esta es una pregunta bastante popular, así que publicaré mi solución.
Tuve el mismo problema y, aunque no es lo ideal, creo que funciona bastante bien y que no depende en parte de la vista.
Mi escenario era que una acción era accesible por sí misma, pero también podía integrarse en una vista: un mapa de Google.

En mi _layout tengo:

@RenderSection("body_scripts", false)

En mi vista de index tengo:

@Html.Partial("Clients") @section body_scripts { @Html.Partial("Clients_Scripts") }

En la vista de mis clients tengo (todo el mapa y assoc. Html):

@section body_scripts { @Html.Partial("Clients_Scripts") }

La vista My Clients_Scripts contiene el javascript que se representará en la página.

De esta manera, mi secuencia de comandos se aísla y puede representarse en la página donde sea necesario, con la etiqueta body_scripts solo representada en la primera aparición que el motor de la vista de la máquina de afeitar encuentra.

Eso me permite tener todo separado: es una solución que funciona bastante bien para mí, otros pueden tener problemas con eso, pero parchea el agujero "por diseño".


Esto me funcionó permitiéndome ubicar conjuntamente javascript y html para una vista parcial en el mismo archivo. Ayuda con el proceso de pensamiento para ver html y parte relacionada en el mismo archivo de vista parcial.

En la vista que utiliza la vista parcial llamada "_MyPartialView.cshtml"

<div> @Html.Partial("_MyPartialView",< model for partial view>, new ViewDataDictionary { { "Region", "HTMLSection" } } }) </div> @section scripts{ @Html.Partial("_MyPartialView",<model for partial view>, new ViewDataDictionary { { "Region", "ScriptSection" } }) }

En el archivo de vista parcial

@model SomeType @{ var region = ViewData["Region"] as string; } @if (region == "HTMLSection") { } @if (region == "ScriptSection") { <script type="text/javascript"> </script"> }


Hay una falla fundamental en la forma en que pensamos acerca de la web, especialmente cuando usamos MVC. La falla es que JavaScript es de alguna manera la responsabilidad de la vista. Una vista es una vista, JavaScript (de comportamiento o de otro tipo) es JavaScript. En Silverlight y el patrón MVVM de WPF, nos enfrentamos a "ver primero" o "modelar primero". En MVC siempre debemos tratar de razonar desde el punto de vista del modelo y JavaScript es una parte de este modelo de muchas maneras.

Sugeriría usar el patrón AMD (a mí me gusta RequireJS ). Separe su JavaScript en módulos, defina su funcionalidad y conéctese a su html desde JavaScript en lugar de confiar en una vista para cargar el JavaScript. Esto limpiará su código, separará sus inquietudes y le facilitará la vida de una sola vez.


Hay una forma de insertar secciones en vistas parciales, aunque no es bonita. Debe tener acceso a dos variables desde la vista principal. Dado que parte del propósito de su vista parcial es crear esa sección, tiene sentido requerir estas variables.

Esto es lo que parece insertar una sección en la vista parcial:

@model KeyValuePair<WebPageBase, HtmlHelper> @{ Model.Key.DefineSection("SectionNameGoesHere", () => { Model.Value.ViewContext.Writer.Write("Test"); }); }

Y en la página insertando la vista parcial ...

@Html.Partial(new KeyValuePair<WebPageBase, HtmlHelper>(this, Html))

También puede utilizar esta técnica para definir los contenidos de una sección mediante programación en cualquier clase.

¡Disfrutar!


La idea de Plutón de una manera más agradable:

CustomWebViewPage.cs:

public abstract class CustomWebViewPage<TModel> : WebViewPage<TModel> { public IHtmlString PartialWithScripts(string partialViewName, object model) { return Html.Partial(partialViewName: partialViewName, model: model, viewData: new ViewDataDictionary { ["view"] = this, ["html"] = Html }); } public void RenderScriptsInBasePage(HelperResult scripts) { var parentView = ViewBag.view as WebPageBase; var parentHtml = ViewBag.html as HtmlHelper; parentView.DefineSection("scripts", () => { parentHtml.ViewContext.Writer.Write(scripts.ToHtmlString()); }); } }

Vistas / web.config:

<pages pageBaseType="Web.Helpers.CustomWebViewPage">

Ver:

@PartialWithScripts("_BackendSearchForm")

Parcial (_BackendSearchForm.cshtml):

@{ RenderScriptsInBasePage(scripts()); } @helper scripts() { <script> //code will be rendered in a "scripts" section of the Layout page </script> }

Página de diseño:

@RenderSection("scripts", required: false)


La primera solución que se me ocurre es usar ViewBag para almacenar los valores que se deben representar.

Una vez, nunca intenté si esto funciona desde una vista parcial, pero debería imo.


Las secciones no funcionan en vistas parciales y eso es por diseño. Puede usar algunos ayudantes personalizados para lograr un comportamiento similar, pero honestamente es responsabilidad de la vista incluir los scripts necesarios, no la responsabilidad parcial. Recomendaría usar la sección @scripts de la vista principal para hacer eso y no preocuparse por los parciales de los scripts.


No puedes necesitar usar secciones en vista parcial.

Incluir en su Vista Parcial. Ejecuta la función después de jQuery cargado. Puede alterar la cláusula de condición de su código.

<script type="text/javascript"> var time = setInterval(function () { if (window.jQuery != undefined) { window.clearInterval(time); //Begin $(document).ready(function () { //.... }); //End }; }, 10); </script>

Julio spader


Resolví esta ruta completamente diferente (porque tenía prisa y no quería implementar un nuevo HtmlHelper):

Envolví mi vista parcial en una gran declaración if-else:

@if ((bool)ViewData["ShouldRenderScripts"] == true){ // Scripts }else{ // Html }

Luego, llamé al Parcial dos veces con un ViewData personalizado:

@Html.Partial("MyPartialView", Model, new ViewDataDictionary { { "ShouldRenderScripts", false } }) @section scripts{ @Html.Partial("MyPartialView", Model, new ViewDataDictionary { { "ShouldRenderScripts", true } }) }


Si lo desea, puede usar una carpeta / index.cshtml como página maestra y luego agregar los scripts de sección. Luego, en tu diseño tienes:

@RenderSection("scripts", required: false)

y su index.cshtml:

@section scripts{ @Scripts.Render("~/Scripts/file.js") }

y funcionará sobre todas tus visitas parciales. Funciona para mi


Si tiene una necesidad legítima de ejecutar algunos js de forma partial , aquí le explicamos cómo podría hacerlo, jQuery es obligatorio:

<script type="text/javascript"> function scriptToExecute() { //The script you want to execute when page is ready. } function runWhenReady() { if (window.$) scriptToExecute(); else setTimeout(runWhenReady, 100); } runWhenReady(); </script>


Siguiendo el principio unobtrusive , no es muy necesario que "_myPartial" inyecte contenido directamente en la sección de scripts. Puede agregar esos scripts de vista parcial en un archivo .js separado y consultarlos en la sección @scripts de la vista principal.


Tuve este problema y utilicé this técnica.

Es la mejor solución que he encontrado que es muy flexible.

También vote here para agregar soporte para la declaración de la sección acumulativa


Tuve un problema similar, donde tuve una página maestra de la siguiente manera:

@section Scripts { <script> $(document).ready(function () { ... }); </script> } ... @Html.Partial("_Charts", Model)

pero la vista parcial dependía de algún JavaScript en la sección de Scripts. Lo resolví codificando la vista parcial como JSON, cargándola en una variable de JavaScript y luego usé esto para rellenar un div, así que:

@{ var partial = Html.Raw(Json.Encode(new { html = Html.Partial("_Charts", Model).ToString() })); } @section Scripts { <script> $(document).ready(function () { ... var partial = @partial; $(''#partial'').html(partial.html); }); </script> } <div id="partial"></div>


Usando Mvc Core puede crear una secuencia de scripts TagHelper ordenada como se ve a continuación. Esto podría transformarse fácilmente en una etiqueta de section donde también le da un nombre (o el nombre se toma del tipo derivado). Tenga en cuenta que la inyección de dependencias debe configurarse para IHttpContextAccessor .

Al agregar scripts (por ejemplo, en un parcial)

<scripts> <script type="text/javascript"> //anything here </script> </scripts>

Al generar los scripts (por ejemplo, en un archivo de diseño)

<scripts render="true"></scripts>

Código

public class ScriptsTagHelper : TagHelper { private static readonly object ITEMSKEY = new Object(); private IDictionary<object, object> _items => _httpContextAccessor?.HttpContext?.Items; private IHttpContextAccessor _httpContextAccessor; public ScriptsTagHelper(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { var attribute = (TagHelperAttribute)null; context.AllAttributes.TryGetAttribute("render",out attribute); var render = false; if(attribute != null) { render = Convert.ToBoolean(attribute.Value.ToString()); } if (render) { if (_items.ContainsKey(ITEMSKEY)) { var scripts = _items[ITEMSKEY] as List<HtmlString>; var content = String.Concat(scripts); output.Content.SetHtmlContent(content); } } else { List<HtmlString> list = null; if (!_items.ContainsKey(ITEMSKEY)) { list = new List<HtmlString>(); _items[ITEMSKEY] = list; } list = _items[ITEMSKEY] as List<HtmlString>; var content = await output.GetChildContentAsync(); list.Add(new HtmlString(content.GetContent())); } } }


Puede usar estos métodos de extensión : (Guardar como PartialWithScript.cs)

namespace System.Web.Mvc.Html { public static class PartialWithScript { public static void RenderPartialWithScript(this HtmlHelper htmlHelper, string partialViewName) { if (htmlHelper.ViewBag.ScriptPartials == null) { htmlHelper.ViewBag.ScriptPartials = new List<string>(); } if (!htmlHelper.ViewBag.ScriptPartials.Contains(partialViewName)) { htmlHelper.ViewBag.ScriptPartials.Add(partialViewName); } htmlHelper.ViewBag.ScriptPartialHtml = true; htmlHelper.RenderPartial(partialViewName); } public static void RenderPartialScripts(this HtmlHelper htmlHelper) { if (htmlHelper.ViewBag.ScriptPartials != null) { htmlHelper.ViewBag.ScriptPartialHtml = false; foreach (string partial in htmlHelper.ViewBag.ScriptPartials) { htmlHelper.RenderPartial(partial); } } } } }

Use así:

Ejemplo parcial: (_MyPartial.cshtml) Ponga el html en el if, y el js en el else.

@if (ViewBag.ScriptPartialHtml ?? true) <p>I has htmls</p> } else { <script type="text/javascript"> alert(''I has javascripts''); </script> }

En su _Layout.cshtml, o donde quiera que se representen los scripts de los parciales, coloque lo siguiente (una vez): solo mostrará el javascript de todos los parciales en la página actual en esta ubicación.

@{ Html.RenderPartialScripts(); }

Luego, para usar su parcial, simplemente haga esto: solo mostrará el html en esta ubicación.

@{Html.RenderPartialWithScript("~/Views/MyController/_MyPartial.cshtml");}


Tuve el mismo problema resuelto con esto:

@section ***{ @RenderSection("****", required: false) }

Esa es una forma bonita de inyectar, supongo.


Supongamos que tiene una vista parcial llamada _contact.cshtml, su contacto puede ser legal (nombre) o un sujeto físico (nombre, apellido). su vista debe tener cuidado con lo que se representa y que se puede lograr con javascript. por lo que puede ser necesaria la reproducción retrasada y la vista interior JS.

La única forma en que pienso, cómo se puede omitir, es cuando creamos una forma discreta de manejar tales preocupaciones de UI.

También tenga en cuenta que MVC 6 tendrá un llamado componente de visualización, incluso los futuros de MVC tenían algunas cosas similares y Telerik también admite tal cosa ...