简体   繁体   English

在.js文件中导入名称空间

[英]Import namespace in .js file

I am working on an MVC application and all the JavaScript for the pages is in their own JavaScript files, so there are no Script tags on the pages. 我正在使用MVC应用程序,并且页面的所有JavaScript都在其自己的JavaScript文件中,因此页面上没有Script标记。 Now, there is a Messages class that contains Errors, Information and Confirmation classes with Static strings. 现在,有一个Messages类,其中包含带有静态字符串的Errors,Information和Confirmation类。 The error messages and information messages are being returned from the server, which is fine. 从服务器返回错误消息和信息消息,这很好。 But the confirmation messages (eg. Do you wish to Save (OK/Cancel), which is the confirm function in JavaScript) are hard coded in each JavaScript file. 但是确认消息(例如,您希望保存(确定/取消),这是JavaScript中的确认功能)在每个JavaScript文件中进行了硬编码。 I now want the JavaScript to use the confirmation messages from the Messages.Confirmation class. 现在,我希望JavaScript使用Messages.Confirmation类中的确认消息。

Currently, to solve this I do something like this in my page, 目前,要解决此问题,我需要在页面中执行以下操作,

<%@ Import Namespace="Business.Common" %> 

.....

<script type="text/javascript">
    confirmSaveQuestion= '<%= Messages.Confirmations.CONFIRM_SAVE  %>';
</script>

and my .js file looks like this 我的.js文件看起来像这样

var confirmSaveQuestion;

function ConfirmSave() {
    var result = window.confirm(confirmSaveQuestion);
    if (result)
        return true;
    else
        return false;
}

and this works fine. 而且效果很好。

Is it possible to import the namespace Business.Common into the .js file, so that I don't have to set the value for confirmSaveQuestion in my page? 是否可以将命名空间Business.Common导入到.js文件中,这样我就不必在页面中设置ConfirmSaveQuestion的值?

Your .js files are static, so there is no way for them to interact with server code. 您的.js文件是静态的,因此它们无法与服务器代码进行交互。 I'd recommend one of two things: 我建议以下两件事之一:

1) Use an ASHX handler to dynamically build javascript files - this will return your javascript dynamically, so that you can inject it with server stuff. 1)使用ASHX处理程序动态生成javascript文件-这将动态返回您的javascript,以便您可以向其中注入服务器内容。 Instead of referencing a .js file in your markup, you would reference your .ashx file. 而不是在标记中引用.js文件,而是应引用.ashx文件。

2) Put the <%= %> tags into your master page - still shows up on the page, but at least you only have to deal with them once. 2)将<%= %>标记放入您的母版页-仍显示在页面上,但是至少您只需要处理一次即可。

As I can't import namespace to my .js file, I went with a different solution. 由于无法将名称空间导入我的.js文件,因此我采用了另一种解决方案。 I removed the script tags from my page and instead added the following line of code. 我从页面上删除了脚本标记,而是添加了以下代码行。 I guess it probably ends up doing a similar sort of thing, but it looks a bit cleaner. 我想它可能最终会做类似的事情,但是看起来有点干净。

<% Html.Telerik().ScriptRegistrar().OnDocumentReady("confirmSaveQuestion = '" + Messages.Confirmations.CONFIRM_SAVE + "'"); %>  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM