Category Archives: BundleConfig

BundleConfig

[RESOLVED]MVC Bundling & Minification Problem

Hi, I have bundled my JS files as follows in BundleConfig.cs

bundles.Add(new ScriptBundle("~/bundles/js").Include(
               "~/js/jquery/jquery.min.js",
               "~/js/jquery/jquery.mousewheel.js",
               "~/js/jquery/jquery.widget.min.js",
               "~/js/metro.min.js",
               "~/js/prettify/prettify.js",
               "~/js/load-metro.js",
               "~/js/docs.js",
               "~/js/github.info.js"));

In my Layout I have following in head section:

@Scripts.Render("~/bundles/js")

I have a view studentdetials.cshtm in student folder which is not rendering as expected.

In the browser error console I get following 404 – not found error:

Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:1568/Student/js/metro.min.js?_=1413550048924

metro.min.js is not inside the student folder but "JS" folder which is in root of the project directory, however my view is searching it inside the student/js/ folder.

Please let me know what I am missing.

Thanks & Regards

Hi Siteslayer,

I have faced similar issue. Actually during bundling, framework manages js files.

In release mode, you will getting this error but not in debug mode, if i understood the problem correctly.

I am getting this problem in debug mode.

Hi siteslayer,

Thanks for your post.

 You can   Use the F12 Developer Tools to Debug JavaScript Errors.

Bundling and minification is enabled or disabled by setting the value of the debug  attribute in the

compilation Element

 in the Web.config file. In the following XML,debug is  set to true so bundling and minification is disabled.

<system.web>
    <compilation debug="true" />
    <!-- Lines removed for clarity. -->
</system.web>

To enable bundling and minification, set the debug value to  "false".

public static void RegisterBundles(BundleCollection bundles)
{
    //bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                 "~/Scripts/jquery-{version}.js"));

    // Code removed for clarity.
    BundleTable.EnableOptimizations = true;
}

Hope this can be helpful.

Best Regards,

Eileen

Eileen ni – MSFT

Hi siteslayer,

Thanks for your post.

 You can   Use the F12 Developer Tools to Debug JavaScript Errors.

Bundling and minification is enabled or disabled by setting the value of the debug  attribute in the

compilation Element

 in the Web.config file. In the following XML,debug is  set to true so bundling and minification is disabled.

<system.web>
    <compilation debug="true" />
    <!-- Lines removed for clarity. -->
</system.web>

To enable bundling and minification, set the debug value to  "false".

public static void RegisterBundles(BundleCollection bundles)
{
    //bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                 "~/Scripts/jquery-{version}.js"));

    // Code removed for clarity.
    BundleTable.EnableOptimizations = true;
}

Hope this can be helpful.

Best Regards,

Eileen

Thanks a lot Eileen, that solved the problem. 

[RESOLVED]Javascript section doesnt fire on click of button?

I am trying to load partial view in a main view based on Ajax on click of a button.

The javascript doesn’t get fired. What is wrong?

<script type="text/javascript">
    $(document).ready(function () {
        $('#btnLoad').click(function () {
            alert("i am in");
            $.ajax({
                type: 'GET',
                url: '/Role/Add',
                dataType: "html",
                success: function (content) {
                    $('#partialcontent').html(content);
                },
                error: function (e) { }
            });
        });
    });

</script>
<div style="float:right">
      
        <input id="btnLoad" type="button" value="click to add" />
</div>
<div id="partialcontent">

 </div>

The code itself looks OK as far as handling the click event. perhaps it’s the placement of the script? Or maybe it’s not rendering on the client. Do a view source on the page and make sure you see that script block in the rendered html. 

Hi Abhi,

Your code is fine. Can you show us the complete code to debug?

@model IEnumerable<RModel>

@{
    Layout = "~/Areas/Feature/Views/Shared/Administrator.cshtml";
}

<style>
    .background {
        background-color: Red;
        font-weight: 700;
    }
</style> 
<script type="text/javascript">
    $(document).ready(function () {
        $('#btnLoad').click(function () {
            alert("i am in");
            $.ajax({
                type: 'GET',
                url: '/Feature/Add',
                dataType: "html",
                success: function (content) {
                    $('#partialcontent').html(content);
                },
                error: function (e) { }
            })
        });

        var tr = $('#tlbRoleinfo').find('tr');
        tr.bind('click', function (e) {
            $(this).addClass('background');
            var id = $(this).closest('tr').children('td:eq(0)').text();
            $.ajax({
                type: "GET",
                url: "/Feature/Edit/" + id,
                dataType: "html",
                success: function (evt) {
                    $('#partialcontent').html(evt);
                },
                error: function (req, status, error) {
                    alert("Error!Occured");
                }
            });
        });
        tr.bind('mouseleave', function (e) {
            $(this).removeClass('background');
        });
    });

</script>

<div>
    <div style="float:right">
        <input id="btnLoad" type="button" value="click to add" />
    </div>
</div>

<div>
    <div>
        <div>
            <table id="tlbRoleinfo">
                    <tr>
                        <th>Feature</th>
                        <th>Description</th>
                    </tr>
                    @foreach (var item in Model)
                    {
                        <tr>
                            <td>  @Html.DisplayFor(modelitem => item.Feature)</td>
                            <td>  @Html.DisplayFor(modelitem => item.Featuredescription)</td>
                        </tr>
                    }
                
            </table>
        </div>
    </div>
    <div id="partialcontent">

    </div>
</div>

This how main view looks in which i am trying to load PartialEdit view and PartialAdd view via Ajax.

I see another error at line 38 like below

Unhandled exception at line 38, column 5 in http://localhost:49843/en/admin/Role

0x800a1391 – JavaScript runtime error: ‘$’ is undefined

you need to add a reference to the jquery script 

@model IEnumerable<RModel>

@{
    Layout = "~/Areas/Feature/Views/Shared/Administrator.cshtml";
}

<style>
    .background {
        background-color: Red;
        font-weight: 700;
    }
</style> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('#btnLoad').click(function () {
            alert("i am in");
            $.ajax({
                type: 'GET',
                url: '/Feature/Add',
                dataType: "html",
                success: function (content) {
                    $('#partialcontent').html(content);
                },
                error: function (e) { }
            })
        });

        var tr = $('#tlbRoleinfo').find('tr');
        tr.bind('click', function (e) {
            $(this).addClass('background');
            var id = $(this).closest('tr').children('td:eq(0)').text();
            $.ajax({
                type: "GET",
                url: "/Feature/Edit/" + id,
                dataType: "html",
                success: function (evt) {
                    $('#partialcontent').html(evt);
                },
                error: function (req, status, error) {
                    alert("Error!Occured");
                }
            });
        });
        tr.bind('mouseleave', function (e) {
            $(this).removeClass('background');
        });
    });

</script>

<div>
    <div style="float:right">
        <input id="btnLoad" type="button" value="click to add" />
    </div>
</div>

<div>
    <div>
        <div>
            <table id="tlbRoleinfo">
                    <tr>
                        <th>Feature</th>
                        <th>Description</th>
                    </tr>
                    @foreach (var item in Model)
                    {
                        <tr>
                            <td>  @Html.DisplayFor(modelitem => item.Feature)</td>
                            <td>  @Html.DisplayFor(modelitem => item.Featuredescription)</td>
                        </tr>
                    }
                
            </table>
        </div>
    </div>
    <div id="partialcontent">

    </div>
</div>

that should do the trick

you only have to add a reference to the script in your ‘main’ view your partials will read the script from their parent. so scripts in your partial views should just work

Do i need to separately reference to the jquery script? In MVC 5 all the Jquery is in project by default.

When you have these types of problems you can press F12 in the browser and review the console window which will show Javascript and JQuery errors.  Maybe that will help you.

Hi abhi0410,

Thanks for your post.

abhi0410

Do i need to separately reference to the jquery script? In MVC 5 all the Jquery is in project by default.

Not exactly,you can add the Jquery script reference to Layout.cshtml and then add the layout to your view what you used.

Of course,you also add separately it on your view.

Hope this can be helpful.

Best Regards,

Eileen

Hi Eileen,

I have done that. I have my jquery files added to my layout.cshtml and script is in my view files.

abhi0410

Hi Eileen,

I have done that. I have my jquery files added to my layout.cshtml and script is in my view files.

you’re using another layout file:

    Layout = "~/Areas/Feature/Views/Shared/Administrator.cshtml";

check if you referenced the jquery script in there

Yes. That is my Admin layout. I have give different name for layout.cshtml.

Hi abhi0410,

Thanks for your reply.

please check if you register Jquery version in BundleConfig.cs,like this:

 bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

Hope this can be helpful.

Best Regards,

Eileen

Hi Eileen,

Yes it is added.

Hi abhi0410,

Thanks for your reply.

if you  have registered Jquery version in BundleConfig.cs and then you need to add this in layout

@Scripts.Render("~/bundles/jquery")

Hope this can be helpful.

Best Regards,

Eileen

[RESOLVED]Why is The Browser Caching An Old Version of my JS File?

I’m working and testing strictly on the dev machine (MVC 4.0), nothing deployed as yet. I created some helpful js routines and placed them in a js file. Later I edited the file but Firefox is still using the old version (cached I surmise). I hear that MVC
was supposed to nullify this caching by computing a hash of the file, appending it to the url’s query string (serving as the new version number), thus embedding a new  <script src=url> onto the page. I looked at my rendered page hoping to see such a hash appended
to the url but all I see is this:
 <script src="/Family/Scripts/MyUtilities.js"></script>
In my bundles loader I have:
    bundles.Add(new ScriptBundle("~/bundles/MyUtilities").Include("~/Scripts/MyUtilities.js"));
and the View page invokes it like this:
    @Scripts.Render("~/bundles/MyUtilities")                  
What am I doing wrong?

I think it’s no longer cached, I don’t know if it’s because I restarted both the app and the browser,

Why don’t my rendered <script src=url> tags have a hash/version number? I’m hoping to prevent this problem recurring in the future.

Hi jal2,

jal2

Why don’t my rendered <script src=url> tags have a hash/version number? 

The browser cache files base on the URL. So you could add parameter to the URL.

<script src="~/Scripts/Files/Te.js?version=1.0"></script>

Best Regards

Starain

Ok thanks. But isn’t MVC 4 supposed  to automatically append a hash/version-no if you use the @Scripts.Render(‘my bundle’) syntax? I thought I read such somewhere.

It does, if optimizations are enabled and the argument to the Scripts.Render() method is a bundle name and it could create the bundle response to calculate the hash value for.

About the first part in that sentence: Depending on what template you used, BundleTable.EnableOptimizations may be set in BundleConfig.cs. If not set, it depends on the "debug" value from the <compilation>-node in web.config.

About the second part: Scripts.Render() has special handling when passed a bundle name (which is what you are after), but if it is a path to a file it just renders an ordinary <script>-tag without the hash.

Your description of the problem suggests you haven’t enabled optimizations, or you are debugging, or you used the path to the javascript file and not the bundle name.

I set BundleTable.EnableOptimizations = true in global.asax and got immediate success. Thanks!

[RESOLVED]Themes/Skins in MVC

Hello All,

I am trying to implement themes/skins in MVC application. So, which are the best ways to implement it ?

My application will have different clients and every client will have different themes. Based on the client I want apply the themes/skins.

For e,g,

  1. localhost/MyProject/Client=A      /// Apply the red theme
  2. localhost/MyProject/Client=B     /// Apply the blue theme

Thanks !

Hi,

there’s no direct equivalent of skins in MVC like you have in webforms.

However you can make use of CSS to make your site to look & feel different. Simply load up a different CSS file depending on a parameter like clientID.

Grz, Kris.

XIII

Hi,

However you can make use of CSS to make your site to look & feel different. Simply load up a different CSS file depending on a parameter like clientID.

Grz, Kris.

Yeah. I thought So. trying to load from BundleConfig but I am not able to do that.

Can you give any example of it ?

Hi,

Post your BundleConfig, Make sure that you do not have wrong order. also order on .cshtml.

Have fun

jsiahaan

Hi,

Post your BundleConfig, Make sure that you do not have wrong order. also order on .cshtml.

Have fun

Ok.. that problem has been solved. Thanks for the help…

However, I would like know how can I change the theme on drop down list index changed OR any other method ???

Hi rohitpundlik,

Thanks for your post.

I think you can’t change the theme on dropdownlist index changed,but you can change the dropdownlist style.or you can customize the look and feel of your site.please check these:

How to style MVC3/ASP.net DropDownList?

Adding a css class to select using @Html.DropDownList()

multi Themes in asp.net mvc 4

Hope this can be helpful.

Best Regards,

Eileen

[RESOLVED]Help bundles on MVC5

i just start use mvc5. And i want dont use bootstrap default. But it have error when i change content bootstrap. I have try bind in BundleConfig.cs but it fail and appear error:

error image

There is my bundles

bundles.Add(new StyleBundle("~/Content/css").Include(
                   "~/Content/site.css"
                  ));
        bundles.Add(new StyleBundle("~/Content/dist/Edit/css").Include(
            "~/Content/dist/Edit/bootstrap.css"
            ));

Thanks for read.

In the Image, you have passed two url of contents into the @Scripts.Render.

Once you have included more than one contents into a bundle means that is bound to thatbundle. So you use only the bundle name, not each content that you have included.

Thanks.

Thanks. 

I have find  error in 

BundleTable.EnableOptimizations = true;

Change value to FALSE, it wil work.

Thanks.

SimpleMembership to get UserName based from UserId

I am using SimpleMembership but I get this error "You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class." I even initialize the membership at Startup but still same
error.

Product Properties

using WebMatrix.WebData;

namespace WebsiteName.POCO
{
[InitializeSimpleMembership]
public class ProductList
{
public int ProductID { get; set; }

public int CategoryID { get; set; }

public int CustomerID { get; set; }

public string CustomerUserName {
get {
SimpleMembershipProvider provider = new SimpleMembershipProvider();

//return provider.GetUserNameFromId(123);
return provider.GetUserNameFromId(CustomerID); //<<<---error here

//int ppp = WebSecurity.GetUserId(WebSecurity.CurrentUserName); //<<<---this works but I'm looking for the username based from user id
}
set {}
}
}
}

Global

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();

GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}

public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new InitializeSimpleMembershipAttribute());
}
}

imperialx

Have you try adding this to _AppStart.cshtml for your project:

@{
    WebSecurity.InitializeDatabaseConnection("DATABASENAME", "USERNAMETABLE", "USERNAMECOLUMN", "USERNAMEMAIL", true);
}

a-rad

@{ WebSecurity.InitializeDatabaseConnection("DATABASENAME", "USERNAMETABLE", "USERNAMECOLUMN", "USERNAMEMAIL", true); }

Yes I did, but same issue. :(

using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Threading;
using System.Web.Mvc;
using WebMatrix.WebData;

namespace WebsiteName.Filters
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
    {
        private static SimpleMembershipInitializer _initializer;
        private static object _initializerLock = new object();
        private static bool _isInitialized;

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // Ensure ASP.NET Simple Membership is initialized only once per app start
            LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
        }

        private class SimpleMembershipInitializer
        {
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Create the SimpleMembership database without Entity Framework migration schema
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    WebSecurity.InitializeDatabaseConnection("DefaultConnectionString", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        }
    }
}

imperialx

There is a fully working example of Single Membership in the starter site.

[RESOLVED]Jquery in Scriptmanager

Visual Studio put this in for me:
 <asp:ScriptManager runat="server">
            <Scripts>
                <asp:ScriptReference Name="jquery" />
            </Scripts>
</asp:ScriptManager>
How does Asp.Net know which version if Jquery to pick? Where is it loaded from?
What am I missing?

You likely already have a particular reference to it defined and it included within your current project or solution (you might check a Scripts folder if one is present). You can also check either the Global.asax file if one is present or the BundleConfig.cs
file within the App_Start folder and you should see a mapping that looks something like this :

ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition
{
        // Code omitted for brevity
}); 

Within this, you’ll see a bit of code that should specify your jQuery location.

Your code make sense but does not exist in my project.

I found this line in Package.config:

<package id="AspNet.ScriptManager.jQuery" version="1.10.2" targetFramework="net45" />

(that is convoluted)

The Package.config file generally indicates that you are using NuGet to load packages for your project. In this case, a particular package called
AspNet.ScriptManager.jQuery, which as mentioned here will do the following:

"This package contains the AspNet.ScriptManager.jQuery assembly that will automatically register jQuery 1.10.2 with the ScriptManager as "jquery".

You should have some code after installing this package that explicitly demonstrates this occurring (try searching your project and it’s code files for "jquery") if you cannot find any that look like your ScriptManager pointing to a particular file,
then it’s likely just being handled from a reference within the package itself.