Ad

Proper Way To Move Multiple .js Includes Into One Include?

- 1 answer

I have 2 Razor .cshtml files that have a similar structure like the following:

<script type="text/javascript" src='@Url.Content("~/Scripts/jqwidgets/jqxcore.js")'></script>
<script type="text/javascript" src='@Url.Content("~/Scripts/jqwidgets/jqxdata.js")'></script>
<script type="text/javascript" src='@Url.Content("~/Scripts/jqwidgets/jqxbuttons.js")'></script>
...

<More header stuff (different in both files)>

<script language="javascript" type="text/javascript">
   function commonFunctionForJqWidgets() {
      ...
      callSomethingFromJqWidgetsLibrary();
      ...
   }
</script>

I am writing common code for these 2 files and would like to put the common code in another .js (or .cshtml) file instead of duplicating it in both places. However, the common code requires including some of the jqwidgets includes since it calls library functions for it.

What would be the proper way to handle this? Should I simply add a new .cshtml file, move all of the includes in there, and then define my common functions in there as well?

Ad

Answer

Usually when you have common UI code, you may put that inside a partial view which can be included in other views as needed. But in your case, It is more like a bunch of javascript files you want in multiple files. So you may create a script bundle which will have all those scripts and use that in your pages as needed.

public class BundleConfig
{

    public static void RegisterBundles(BundleCollection bundles)
    {
        // Your existing bundles here

        bundles.Add(new ScriptBundle("~/bundles/jQxWidgets")
                  .Include(
                  "~/Scripts/jqwidgets/jqxcore.js",
                  "~/Scripts/jqwidgets/jqxdata.js",
                  "~/Scripts/jqwidgets/jqxbuttons.js",
                  "~/Scripts/SomeOtherCustomJsfileRelatedtojQxWidgets.js"));
    }
}

And in your specific views, you can include this inside the Scripts section.

@section Scripts
{
  @Scripts.Render("~/bundles/jQxWidgets")
}

Or if you have more than just the scripts as your common stuff, create a partial view and include your common stuff there and include this partial view in your other views as needed.

Create a partial view called CommonGrid.cshtml inside your ~/Views/Shared folder

<h2>Common header for both the pages </h2>
@section Scripts
{
  @Scripts.Render("~/bundles/jQxWidgets")
}

And in your other views

UserList.cshtml

<h1>Users</h1>
@Html.Partial("CommonGrid")

ProductList.cshtml

<h1>Products</h1>
@Html.Partial("CommonGrid")

You can also make your CommonGrid strongly typed to a view model and create a property in your page specific view model of this type(of CommonGrid's viewmodel) and pass that in the Html.Partial method.

Ad
source: stackoverflow.com
Ad