问题
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