How to add a script in a partial view in MVC4?

前端 未结 9 1925
天涯浪人
天涯浪人 2020-12-05 09:15

This is the code which I have in my partial view

@model Contoso.MvcApplication.Models.Exercises.AbsoluteArithmetic

@using(Html.BeginForm())
{
相关标签:
9条回答
  • 2020-12-05 10:05

    This worked for me allowing me to colocate JavaScript and HTML for partial view in same file for ease of readability

    In View which uses Partial View called "_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" } })
    
     }
    

    In Partial View file

    @model SomeType
    
    @{
        var region = ViewData["Region"] as string;
    }
    
    @if (region == "HTMLSection")
    {
    
    
    }
    
    @if (region == "ScriptSection")
    {
            <script type="text/javascript">
        </script">
    }
    
    0 讨论(0)
  • 2020-12-05 10:08

    Check out my answer How to render a Section in a Partial View, which allows you to define Scripts and Styles in any view/partial view. It also takes care of duplicate includes.

    My personal take is that sections aren't a good solution for styles and javascript includes.

    0 讨论(0)
  • 2020-12-05 10:15

    Noob trick: Define a function in an already loaded file, and call the function on partial view load.

    1.Have a separate js file that you load with your usual bundle:

    BundleConfig.cs

    bundles.Add(new ScriptBundle("~/bundles/CustomScripts").Include(
        "~/Scripts/Custom/partial-view.js"
    ));
    
    1. Load the custom script bundle like any other bundle in your layout

    _Layout.cshtml

    @Scripts.Render("~/bundles/CustomScripts");
    
    1. define a function, in our case OnPartialViewLoad function in the custom js file:

    partial-view.js

    function OnPartialViewLoad() {
        // ... your onLoad work
    }
    
    1. add a document.ready() function to the end of your partial view and call the onLoaded function.

    partialView.cshtml

    <script type="text/javascript">
        $(document).ready(function(){
            OnPartialViewLoad();
        });
    </script>
    
    0 讨论(0)
提交回复
热议问题