传递服务器端变量到链接的javascript文件

本文关键字:javascript 文件 链接 服务器端 变量 | 更新日期: 2023-09-27 17:51:01

我正在构建一个多语言web应用程序,其中我有一个。aspx.cs文件

public partial class example:System.Web.UI.Page
{
    private string message="message to be displayed depending on user language";
        public string Message
        {
            get{return message;}

            set{} 
         }    
}

和一个.aspx文件,其中链接了一个用于验证用户输入

的javascript文件。
<html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
     <script type="text/javascript" src="Scripts/DataValidation.js"></script>
    </head>
    <body>
<form id="form1" runat="server" onsubmit="return validation()">
    <asp:TextBox ID="tbSupplierName" CssClass="marginspace" runat="server" Width="150px" MaxLength="30"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" 
                        onclick="btnSearch_Click"   />
</form>
    </body>
    </html>

我的datavalation .js文件看起来像这样

 function validation()
    {
    var SupplierName = document.getElementById('tbSupplierName');
    if (SupplierName.value.length == 0)
    {
    alert('please enter supplier name');//here i want to display server side variable 'message'
    return false;
    }
    }

问题是我想把我的服务器端变量'message'传递给链接的外部javascript文件DataValidation.js,并在警报

中显示它

我已经尝试了下面的代码,但它不工作

function validation()
    {
  var message='<%=Message%>';
    var SupplierName = document.getElementById('tbSupplierName');
    if (SupplierName.value.length == 0)
    {
    alert(message);
    return false;
    }
    }

帮我解决这个问题。

传递服务器端变量到链接的javascript文件

您可以在ASP中声明全局JavaScript变量。净页

 <script>
    message='<%=Message%>';
 </script>

你可以直接在JS文件

中使用它
function validation() {
    var SupplierName = document.getElementById('tbSupplierName');
    if (SupplierName.value.length == 0) {
        alert(message);
        return false;
    }
}