mmssaann
mmssaann

Reputation: 1507

jQuery not defined + MVC4

Im creating the below MVC view that has got some jquery script in it. However this script is not getting executed. Getting jQuery undefined error.

I want to write including script directly in view instead of using layout page.

Can somebody advise what am I doing wrong here?

@{
ViewBag.Title = "FileUpload";
}

<html lang="en">
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title - What up boyeez!</title>
<meta name="viewport" content="width=device-width" />
<script src="~/Scripts/jquery-ui-1.10.0.min.js"></script>

<h2>FileUpload</h2>


@using (Html.BeginForm("UploadFile", "FileUpload", FormMethod.Post, new { enctype =         "multipart/form-data" }))
{
@Html.ValidationSummary();
<ol>
    <li class="lifile">
        <input type="file" id="fileToUpload" name="file" />
        <span class="field-validation-error" id="spanfile"></span>
    </li>
</ol>
<input type="submit" id="btnSubmit"  value="Upload" />
}
</body> 
</html>

   <script type="text/jscript">
   (function ($) {
       function GetFileSize(fileid) {
        try {
            var fileSize = 0;

            if ($.browser.msie) {
                var objFSO = new ActiveXObject("Scripting.FileSystemObject");
                var filePath = $("#" + fileid)[0].value;

                var objFile = objFSO.getFile(filePath);

                var fileSize = objFile.size;
                fileSize = fileSize / 1048576;

            }
            else {
                fileSize = $("#", fileid)[0].files[0].size
                fileSize = file / 1048576;
            }

            return fileSize;

        }
        catch (e) {
            alter("Error is: " + e);
        }
    }

    function getNameFromPath(strFilepath) {
        debugger;

        var objRE = new RegExp(/([^\/\\]+)$/);
        var strName = objRE.exec(strFilepath);

        if (strName == null) {
            return null;
        }
        else {
            return strName[0];
        }
    }

    $("#btnSubmit").live("click", function () {
        debugger;
        if ($('#fileToUpload').val == "") {
            $("#spanfile").html("Please upload file");
            return false;
        }
        else {
            return checkfile();
        }
    });

    function checkfile() {
        var file = getNameFromPath($("#fileToUpload").val());

        if (file != null) {
            var extension = file.subst((file.last('.') + 1));

            switch (extension) {

                case 'jpg':
                case 'png':
                case 'gif':
                case 'pdf':
                    flag = true;
                    break;

                default:
                    flag = false;
            }
        }

        if (flag == false) {
            $("#spanfile").text("You can upload only jpg, png, gif, pdf extension file");
            return false;
        }
        else {
            var size = GetFileSize('fileToUpload');

            if (size > 3) {
                $("#spanfile").text("You can upload file up to 3 MB");
                return false;
            }
            else {
                $("#spanfile").text("");
            }
        }
    }

    $(function () {
        debugger;
        $("#fileToUpload").change(function () {
            checkfile();
        });
    });
   })(jQuery);

Upvotes: 0

Views: 14048

Answers (3)

Flea
Flea

Reputation: 11284

I was having the same problem of client side validation not working. I brought up the JavaScript console in Chrome and saw I was receiving an error stating "JQuery was not defined.".

Turns out I had some code in my View that was causing problems with jQuery not loading.

Recommendation to others who come across this, check your JS console in your browser to ensure you are not getting a JQuery error.

Upvotes: 0

Andy Brown
Andy Brown

Reputation: 19161

You are missing a reference to jquery itself. You probably also want a css file for jquery ui:

<link rel="stylesheet" href="css/themename/jquery-ui.custom.css" />
<script src="js/jquery.min.js"></script>
<script src="js/jquery-ui.custom.min.js"></script> 

See the "Basic Overview: Using jQuery UI on a Web Page" section on the jquery-ui learning docs for full details of how to use and customise jquery ui.

Razor techniques for jquery files

To make your life easier in your view template, you could use the scripts render function:

@Scripts.Render("~/Scripts/jquery-1.9.1.min.js")
@Scripts.Render("~/Scripts/jquery-ui-1.10.0.min.js")

In itself, not too impressive: the syntax is slightly more expressive and 5 characters shorter, that's all.

But it leads you into bundles (references at the end), which are really what you should be using.

Bundles are awesome

Bundles allow you to:

  • Group dependent files: grouping js and/or css files together reduces the chances of this happening, and also means you can "modularise" your own scripts into multiple files in one folder.
  • Increase performance: Send out everything inside a single Bundle in a single file - speeding up load times for clients by reducing the number of http requests from the browser
  • Help development: Use non-minified javascripts (and css) for debugging during development
  • Publish without changes to code: Use the minified scripts for live deployment
    • Use in-built minifying for your own scripts
  • Optimise client experience: Use CDNs for standard scripts like jquery (which is better for your users)
  • Upgrade easily: Not have to change code when you update your version numbers for things like jquery through NuGet by use of the {version} wildcard (as below)

Example:

// This is usually in your MVC 4 App_Start folder at App_Start\BundleConfig
public class BundleConfig {
  public static void RegisterBundles(BundleCollection bundles) {
    // Example with full use of CDNs in release builds
    var jqueryCdnPath = "https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js";
    bundles.Add(new ScriptBundle("~/bundles/jquery", jqueryCdnPath).Include("~/Scripts/jquery-{version}.js"));

And in your razor file you only need a tiny change:

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

This will:

  • send out the full jquery script during debugging
  • send out the minified script for a release build
  • even minify your own bundles such as @Scripts.Render("~/bundles/myScripts"); for live builds

Bundle details

Under the hood bundles will use the CDNs, or minify your own scripts as well, or send already minified files (like jquery-1.9.1.min.js) during release builds, but you can control this by using bundles.UseCdn and BundleTable.EnableOptimizations inside your RegisterBundles method. By using this along with AppSettings in your web.config you can have very close control so that you could even send out debugging scripts for certain users on a live site.

Also note the use of {version} in the bundle configuration.

You can include multiple scripts in a bundle as well:

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

This razor command will now send out both files for you:

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

And you can use bundles for css:

bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
            "~/Content/themes/base/jquery.ui.core.css",
            "~/Content/themes/base/jquery.ui.resizable.css",
            "~/Content/themes/base/jquery.ui.selectable.css",
            "~/Content/themes/base/jquery.ui.accordion.css",
            "~/Content/themes/base/jquery.ui.autocomplete.css",
            "~/Content/themes/base/jquery.ui.button.css",
            "~/Content/themes/base/jquery.ui.dialog.css",
            "~/Content/themes/base/jquery.ui.slider.css",
            "~/Content/themes/base/jquery.ui.tabs.css",
            "~/Content/themes/base/jquery.ui.datepicker.css",
            "~/Content/themes/base/jquery.ui.progressbar.css",
            "~/Content/themes/base/jquery.ui.theme.css"));

References:

Upvotes: 4

user247702
user247702

Reputation: 24212

You're loading the jQuery UI library without loading the jQuery library.

<script src="~/Scripts/path/to/jquery"></script
<script src="~/Scripts/jquery-ui-1.10.0.min.js"></script

Upvotes: 1

Related Questions