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

前端 未结 9 1940
天涯浪人
天涯浪人 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 09:56

    If you want to include specific scripts only in some partial views and avoid spreading them unnecessarily throughout your application, you can do something like this:

    Define a bundle pointing to an empty javascript file in your BundleConfig.cs:

     bundles.Add(new ScriptBundle("~/bundles/empty").Include(
                        "~/Scripts/empty.js"
                ));
    

    In the head section of your _Layout.cshtml, add this variable:

    @{
            ViewBag.AdditionalBundle = String.IsNullOrEmpty(ViewBag.AdditionalBundle) ? "~/bundles/empty" : ViewBag.AdditionalBundle;
        }
    

    In the bottom of your _Layout.cshtml, render any additional bundles you want:

    @Scripts.Render("~/bundles/lib")
        @Scripts.Render(@ViewBag.AdditionalBundle);
        @RenderSection("scripts", required: false)
    

    And finally, in the partial view in which you need any specific scripts, just add the corresponding bundle to the variable:

    ViewBag.AdditionalBundle = "~/bundles/mySpecificBundle";
    

    Partial views are rendered before the _Layout.cshtml, so you need that verification at the top of the file. It goes like this: if any partial view assigned a value to ViewBag.AdditionalBundle, then use it. Otherwise, render an empty script.

提交回复
热议问题