JS file/function referenced in _Layout.cshtml is not working on another Views

99封情书 提交于 2019-12-23 03:30:23

问题


I have some validation related functions that will be used on all my views and are located in an external JS file. I have added the JS reference in the _Layout.cshtml.

My understanding is that if file is referred into _Layout.cshtml, then it would be available for usage in the Views rendered in the layout. However, when I ran some another view for example and inspected it, I see the reference to the JS file "val.js" but it results with an error in the console (probably that error was a reason my validation is not working on another views):

And here is definition of my val.cs file:

(function ($) {
    var defaultOptions = {
        validClass: 'has-success',
        errorClass: 'has-error',
        highlight: function (element, errorClass, validClass) {
            $(element).closest(".form-group")
                .removeClass(validClass)
                .addClass('has-error');
        },
        unhighlight: function (element, errorClass, validClass) {
            $(element).closest(".form-group")
            .removeClass('has-error')
            .addClass(validClass);
        }
    };

    $.validator.setDefaults(defaultOptions);

    $.validator.unobtrusive.options = {
        errorClass: defaultOptions.errorClass,
        validClass: defaultOptions.validClass,
    };
})(jQuery);

So any kind of help would be awesome. Thanks.


回答1:


After stuggling for a few hours, I've found how to solve this, I simply added this to the bottom of my _Layout.cshtml

 @Scripts.Render("~/bundles/jqueryval")
 <script src="@Url.Content("~/Scripts/val.js")"></script>


来源:https://stackoverflow.com/questions/44675436/js-file-function-referenced-in-layout-cshtml-is-not-working-on-another-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!