12

I am using visual studio 2019.

I have a problem which I haven't encountered before - in view, this line (just this line) is throwing error:

@Scripts.Render("~/scripts/scriptCommon")

I've checked bundles config:

ScriptBundle scriptCommon = new ScriptBundle("~/scripts/scriptCommon");
      scriptCommon.Include("~/static/scripts/jquery-1.11.0.min.js");
      scriptCommon.Include("~/static/scripts/bootstrap.min.js");

Both files are on the file system.

This bundle is also added to bundles with:

bundles.Add(scriptCommon);

(just like all the other bundles)

I don't understand why this error? What could be the reason?

Short error message:

System.NullReferenceException: Object reference not set to an instance of an object.

enter image description here

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
   Microsoft.Ajax.Utilities.ActivationObject.DefineField(INameDeclaration nameDecl, FunctionObject fieldValue) +20
   Microsoft.Ajax.Utilities.ActivationObject.DefineLexicalDeclarations() +92
   Microsoft.Ajax.Utilities.BlockScope.DeclareScope() +4
   Microsoft.Ajax.Utilities.ResolutionVisitor.CreateFields(ActivationObject scope) +35
   Microsoft.Ajax.Utilities.ResolutionVisitor.CreateFields(ActivationObject scope) +77
   Microsoft.Ajax.Utilities.ResolutionVisitor.CreateFields(ActivationObject scope) +77
   Microsoft.Ajax.Utilities.ResolutionVisitor.CreateFields(ActivationObject scope) +77
   Microsoft.Ajax.Utilities.ResolutionVisitor.Apply(AstNode node, ActivationObject scope, CodeSettings settings) +62
   Microsoft.Ajax.Utilities.JSParser.Parse(CodeSettings settings) +972
   Microsoft.Ajax.Utilities.Minifier.MinifyJavaScript(String source, CodeSettings codeSettings) +548
   System.Web.Optimization.JsMinify.Process(BundleContext context, BundleResponse response) +92
   System.Web.Optimization.Bundle.ApplyTransforms(BundleContext context, String bundleContent, IEnumerable`1 bundleFiles) +273
   System.Web.Optimization.Bundle.GenerateBundleResponse(BundleContext context) +141
   System.Web.Optimization.Bundle.GetBundleResponse(BundleContext context) +45
   System.Web.Optimization.BundleResolver.GetBundleContents(String virtualPath) +166
   System.Web.Optimization.AssetManager.EliminateDuplicatesAndResolveUrls(IEnumerable`1 refs) +284
   System.Web.Optimization.AssetManager.DeterminePathsToRender(IEnumerable`1 assets) +761
   System.Web.Optimization.AssetManager.RenderExplicit(String tagFormat, String[] paths) +35
   System.Web.Optimization.Scripts.RenderFormat(String tagFormat, String[] paths) +107
   System.Web.Optimization.Scripts.Render(String[] paths) +21
   ASP._Page_Views_CodeBase_CodeBaseTbl_cshtml.Execute() in D:\ROOT\GIT\Franjo_dev01\Solution\fCatEve\fCatEve\Views\CodeBase\CodeBaseTbl.cshtml:9
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +198
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +105
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +78
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +52
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +173
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9849569
   System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
9
  • Are you getting the error in dev or prod env. Check the bundling is enabled in our code. Commented Oct 4, 2019 at 7:31
  • In BundleConfig.cs in the method RegisterBundles I've set BundleTable.EnableOptimizations = true, but the error is still there. What else should I do? Commented Oct 4, 2019 at 8:08
  • 7
    From another answer I've found that problem was ScriptBundle - I've changed this to Bundle and error went away. So, now it's Bundle myBundle = new Bundle("~/bundlename"); What it stopped working the old way all the sudden I don't understand. Commented Oct 4, 2019 at 13:17
  • 1
    Looking at similar issue, some posts suggests that this is due to some "error" in the js file that fails the bundler, in my case bootstrap.js, would be great if the bundler threw exceptions instead of giving us nulls Commented Jun 9, 2021 at 17:42
  • 6
    I had a similar issue when I upgraded my NuGet package from Bootstrap 4 to Bootstrap 5. All of a sudden @Scripts.Render("~/bundles/bootstrap") threw a NullReferenceException. After changing the bundle configuration to use new Bundle instead of new ScriptBundle things magically worked again. I still don't understand why this change was needed. Commented Jun 15, 2021 at 15:20

1 Answer 1

23

Try this, which worked in my system and project:

  1. Open BundleConfig.cs. You should find it at the App_Start folder.
  2. Then change the bundling for your specific script @Scripts.Render("~/scripts/scriptCommon"), from ScriptBundle scriptCommon = new ScriptBundle("~/scripts/scriptCommon"); to Bundle scriptCommon = new Bundle("~/scripts/scriptCommon");

I had a similar problem when upgrading Bootstrap from 4.5 version to 5.*

I set in public static void RegisterBundles(BundleCollection bundles) { ... } method, from:

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

to:

bundles.Add(new Bundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.js"));

Change ScriptBundle into just Bundle.


Additional Troubleshooting

  1. Be sure that after bundling the files, you add the reference to them at the bottom of the view file:
@section Scripts {
    <script src="~/Scripts/youCode.js"></script>
}
  1. Double check that you're referencing correctly the routes to the actual files in your folder structure.

For example, be sure that when installing any of your libraries, your include routes are pointing to the right place.

// Wrong path
bundles.Add(new Bundle("~/bundles/bootstrap").Include("~/Scripts/randomFolderName/bootstrap.js"));
// Correct path
bundles.Add(new Bundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.js"));
  1. Full working example, from one of my NET Framework 4.7.2 projects:
// C:\ ... \FolderSolution\ProjectLevel\App_Start\BundleConfig.cs
using System.Web.Optimization;

namespace MiningTracker.Web
{
    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            #region SCRIPTS

            bundles
                .Add(new ScriptBundle("~/bundles/jquery")
                    .Include(
                        "~/Scripts/jquery-{version}.js",
                        "~/Scripts/jquery-ui.js",
                        "~/Scripts/jquery.blockUI.js",
                        "~/Scripts/jquery.steps.js",
                        "~/Scripts/jquery.steps.min.js",
                        "~/Scripts/jquery.mask.js"));

            bundles
                .Add(new ScriptBundle("~/bundles/datatables")
                    .Include(
                    "~/Scripts/DataTables/jquery.dataTables.min.js",
                    "~/Scripts/DataTables/dataTables.bootstrap5.min.js"));

            bundles
                .Add(new ScriptBundle("~/bundles/jqueryval")
                    .Include("~/Scripts/jquery.validate*")
                    .Include("~/Scripts/validation/jquery_validate-messages_es.js"));

            bundles
                .Add(new ScriptBundle("~/bundles/mvcfoolproof")
                    .Include(
                        "~/Scripts/mvcfoolproof.core.js",
                        "~/Scripts/mvcfoolproof.jquery.validation.js",
                        "~/Scripts/mvcfoolproof.msajax.validation.js",
                        "~/Scripts/mvcfoolproof.unobtrusive.js"
                        ));

            bundles
                .Add(new ScriptBundle("~/bundles/modernizr")
                    .Include("~/Scripts/modernizr-*"));

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

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

            bundles
                .Add(new ScriptBundle("~/content/scripts")
                    .Include("~/Scripts/index.js"));

            bundles
                .Add(new Bundle("~/bundles/bootstrap")
                    .Include(
                        "~/Scripts/bootstrap.bundle.js",
                        "~/Scripts/bootstrap-notify.js"));

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

            #endregion SCRIPTS

            #region STYLES

            // FIX: It is not bundling correctly style on publishing.
            bundles
                .Add(new StyleBundle("~/content/styles")
                    .Include(
                        "~/Content/bootstrap.css",
                        "~/Content/font-awesome.min.css",
                        "~/Content/animate.css",
                        "~/Content/jquery-ui.css",
                        "~/Content/jquery.steps.css",
                        "~/Content/Datatables/css/dataTables.bootstrap5.min.css",
                        "~/Content/site.css",
                        "~/Content/cropperjs/cropper.css",
                        "~/Content/cropperjs/cropper-site.css"
                        ));

            #endregion STYLES
        }
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

To clarify on this answer - WHY this is the case: ScriptBundle invokes a minifier, and if there's an issue (such as new js spec the minifier isn't tested to handle / the script is already minified) then the ScriptBundle return will be null. So to skip the minifying step in bundling, just use the "Bundle" type when adding to your BundleConfig.cs entries. Especially important for dynamically included bundles (as those will fail at runtime and can be hard to test). There's likely an attribute / filter to catch these exceptions and return an empty bundle and log the error instead.
Further reading on bundling basics: tutorialsteacher.com/mvc/…
@Starnutoditopo What is your NET Framework version? In my example, I was using 4.7.2 I added some notes that you may find useful. Let me know more details about your problem.
@carloswm85 Thanks for the update; I'm using .net framework 4.8 and the script paths look correct
@Starnutoditopo Also, be sure that your $("#myId").data("data") line is receiving correctly the data field. I assume that that's an AJAX call. You may have your problem there instead.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.