asp.net - Using java script code in MVC5 - where to put it -
im having mvc5 application , in view index.cshtml need use java script code ,currently put script code inside view , working fine. question should put code (from best practice) , how should refer view?please provide example.
the approach i've written down below way of extracting javascript views.
- better maintain (js issues -> in js files , not in views)
- modular approach
- clear separation
- better understand design
in html5, use data
attribute pass along variables model
. helps tremendously in porting variables mvc (your viewmodel) javascript. allows keep javascript stored in separate files in mvc environment.
1.1 binding c# html
<div class="news" data-js-params="websitename=@locationwebsitehelper.currentlocationwebsitename()&languagename=@languagename&page=0&itemsperpage=@model.maxnumberofitems">
1.2 js helper functions convert data object literals
although built on jquery, i've written 2 small functions can porting querystring variables object literals , back. use these throughout js files:
// @param (qs): query string of key value pairs (without ?) // @param (keydelimiter): string : character between values , keys // @param (valdelimiter): string : character between keys , values // @return (obj): object literal // @example: key1=val1&key2=val2&key3=val3 convertqstoliteral: function (qs, keydelimiter, valdelimiter) { var arrparams, obj = {}; if (qs && qs.length) { keydelimiter = keydelimiter || '&'; valdelimiter = valdelimiter || '='; arrparams = qs.split(keydelimiter); $.each(arrparams, function (i, pair) { var arrpair = pair.split(valdelimiter), key = arrpair[0], val = arrpair[1]; obj[key] = val; }); } return obj; }, // @param (literal): object literal key value paired of 1 level deep // @param (keydelimiter): string character between values , keys // @param (valdelimiter): string : character between keys , values // @return (string): array string representation // @example: { key1: val1, key2: val2, key3: val3 } convertliteraltoqs: function (literal, keydelimiter, valdelimiter) { var arrqs = [], arrpairs, key; keydelimiter = keydelimiter || '&'; valdelimiter = valdelimiter || '='; (key in literal) { if (literal.hasownproperty(key)) { arrpairs = []; arrpairs.push(key, literal[key]); arrqs.push(arrpairs.join(valdelimiter)); } } return arrqs.join(keydelimiter); },
1.3 convert html data js object literals
with these functions in mind can pass query string variables object literal.
var dataparams = convertqstoliteral($('.news').data('js-params')); // data attr var urlparams = convertqstoliteral(window.location.search.substr(1)); // url query string
1.4 example: js modular setup extend , override object literals
combined jquery's $.extend()
function can override javascript objects in modular approach (considering closures js file/module looks this):
window.projectname = (function($, projectname){ // default object literal var cfg = { // default options idea: 'great' }; // @param (options): cfg object projectname.module = function (options) { this.settings = $.extend(true, {}, cfg, options); // deep copy this.init(); }; projectname.module.prototype = { init: function(){ this.idea = this.settings.idea; console.log(this.idea); } }; return projectname; }(window.jquery, window.projectname));
1.5 initializing js module
var module = new projectname.module({ idea: 'even better' });
2.1 adding scripts/css views
you have couple options attaching scripts views/pages/blocks:
- section defined in baselayout (only partial views, directly included baselayout)
- c#
clientresources
(not best approach in mvc still doable, allows include external files partial view -> view in view) - bundles (good or minification , modular approach)
2.2.1 baselayout setup sections
@rendersection("additionaljs", false)
2.2.2 usage partial view
@section additionaljs { <script> var module = new projectname.module({ idea: @model.idea }); </script> }
2.3.1 baselayout setup view in view
@html.raw(html.requiredclientresources(renderingtags.header))
2.3.2 usage view in view
clientresources.requirescript("/design/js/projectname.module.js").atheader();
2.4.1 bundleconfig setup scripts
/// <summary> /// register javascript bundles /// separated in libjs, projectjs , polyfilljs /// </summary> /// <param name="bundles"></param> private static void registerscripts(bundlecollection bundles) { // usage libraries bundles.add(new scriptbundle( "~/bundles/libjs").include( "~/design/js/lib/*.js" )); // project object bundles.add(new scriptbundle( "~/bundles/projectjs").include( "~/design/js/project.dev.js", "~/design/js/classes/*.js", "~/design/js/components/*.js" )); // usage browser support bundles.add(new scriptbundle( "~/bundles/polyfilljs").include( "~/design/js/polyfills/*.js" )); } /// <summary> /// render scripts inside conditional comments /// http://stackoverflow.com/questions/12865939/mvc4-bundling-minification-with-ie-conditional-comments /// </summary> /// <param name="ie"></param> /// <param name="paths"></param> /// <returns></returns> public static ihtmlstring renderconditionalscripts(string ie, params string[] paths) { var tag = string.format("<!--[if {0}]>{1}<![endif]-->", ie, scripts.render(paths)); return new mvchtmlstring(tag); }
2.4.2 baselayout setup
... <head> ... @bundleconfig.renderconditionalscripts("lte ie 9", "~/bundles/polyfilljs") @scripts.render("~/bundles/libjs") <head> <body> ... @scripts.render("~/bundles/projectjs") </body>
Comments
Post a Comment