在MVC5使用Java脚本code - 把它放在哪里 [英] Using java script code in MVC5 - where to put it

查看:111
本文介绍了在MVC5使用Java脚本code - 把它放在哪里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

林有MVC5应用程序,并在视图index.cshtml我需要使用
一些Java脚本code,现在我把视图中的脚本code和其工作的罚款。
我的问题是我应该在哪里把这个code(从最佳实践)以及如何
我指的是从有何看法?请提供一个例子。

Im having MVC5 application and in the view index.cshtml I need to use some java script code ,currently I put the script code inside the view and its working fine. My question is where should I put this code (from best practice) and how should I refer to it from the view?please provide an example.

推荐答案

我下面写下来的方法是从我的意见完全提取的JavaScript的方式。

The approach I've written down below is my way of extracting JavaScript completely from your views.


  • 更好地保持(JS问题 - >看在JS文件,而不是在视图中)

  • 模块化方法

  • 清晰的分离

  • 更好的设计,以了解

在HTML5,使用数据属性从模型一起变量传递
这从MVC(您视图模型)移植变量的JavaScript有极大的帮助。
这也可以让你保持存储在单独的文件JavaScript作为你可能会在MVC环境就好。

In HTML5, use the data attribute to pass along variables from the Model. This helps tremendously in porting variables from MVC (your viewmodel) to javascript. This also allows you to keep javaScript stored in separate files as you probably would like in an MVC environment.

1.1绑定C#中的HTML

<div class="news" data-js-params="websiteName=@LocationWebsiteHelper.CurrentLocationWebsiteName()&amp;languageName=@languageName&amp;page=0&amp;itemsPerPage=@Model.MaxNumberOfItems">

1.2 JS助手功能将数据转换为对象文本

虽然建立在jQuery的,我已经写了2个小功能,它可以帮助移植查询字符串变量转换成目标文字和背部。我使用这些在我的js文件:

Although built on jQuery, I've written 2 small functions which can help porting querystring variables into object literals and back. I use these throughout my js files:

// @param (qs): a query string of key value pairs (without ?)
// @param (keyDelimiter): string : character between values and keys
// @param (valDelimiter): string : character between keys and values
// @return (obj): an 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): an object literal key value paired of one level deep
// @param (keyDelimiter): string  character between values and keys
// @param (valDelimiter): string : character between keys and 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 || '=';

    for (key in literal) {
        if (literal.hasOwnProperty(key)) {
            arrPairs = [];
            arrPairs.push(key, literal[key]);
            arrQs.push(arrPairs.join(valDelimiter));
        }
    }

    return arrQs.join(keyDelimiter);
},

1.3 HTML转换成数据对象的js文字

使用这些功能记住你可以传递任何查询字符串变量一样为对象文本。

With these functions in mind you can pass any query string like variables into an object literal.

var dataParams = convertQsToLiteral($('.news').data('js-params')); // get data attr
var urlParams = convertQsToLiteral(window.location.search.substr(1)); // get url query string

1.4举例:JS模块化安装扩展和覆盖对象文本

使用jQuery的 $扩展()功能相结合,您现在可以覆盖一个模块化的方式JavaScript对象(考虑所有受封一个js文件/模块如下所示):

Combined with jQuery's $.extend() function you can now override javascript objects in a modular approach (considering all closures a js file/module looks like this):

window.ProjectName = (function($, projectname){
    // default object literal
    var cfg = {
        // your default options
        idea: 'great'
    };

    // @param (options): something like the 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初始化模块的js

var module = new ProjectName.Module({ idea: 'even better' });

2.1添加脚本/ css来您的意见

您有附加脚本到你的看法/页/块一对夫妇的选择:

You have a couple options for attaching scripts to your views/pages/blocks:


  • 在定义的baselayout部分(仅限于部分意见,直接纳入的baselayout)

  • C# ClientResources (不MVC,但仍是可行的最好的方法,可以让你包括外部文件到一个局部视图 - >视图视图)

  • 束(好或缩小和模块化的方法)

  • section defined in the baselayout (only for partial views, directly included into the baselayout)
  • c# ClientResources (not the best approach in MVC but still doable, allows you to include external files into a partial view -> view in view)
  • bundles (good or minification and modular approach)

2.2.1的baselayout设置为部分

@RenderSection("AdditionalJS", false)

2.2.2使用局部视图

@section AdditionalJS
{
    <script>
        var module = new ProjectName.Module({ idea: @Model.idea });
    </script>
}

2.3.1的baselayout设置为视图鉴于

@Html.Raw(Html.RequiredClientResources(RenderingTags.Header))

鉴于2.3.2使用视图

ClientResources.RequireScript("/Design/js/projectname.module.js").AtHeader();

2.4.1 BundleConfig设置的脚本

/// <summary>
/// Register the Javascript bundles
/// Separated in libJs, projectJs and polyfillJs
/// </summary>
/// <param name="bundles"></param>
private static void RegisterScripts(BundleCollection bundles)
{
    // usage for 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 for 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设置

...
<head>
    ...
    @BundleConfig.RenderConditionalScripts("lte IE 9", "~/bundles/polyfillJs")
    @Scripts.Render("~/bundles/libJs")
<head>
<body>
    ...
    @Scripts.Render("~/bundles/projectJs")        
</body>

这篇关于在MVC5使用Java脚本code - 把它放在哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆