当从aspx.cs页面传递值时,警告在javascript中显示未定义

alert shows undefined in javascript when passed value form aspx.cs page

本文关键字:警告 javascript 未定义 显示 cs aspx 当从      更新时间:2023-09-26
 string locationName = "Mumbai";
    Page.ClientScript.RegisterStartupScript(Type.GetType
    ("System.String"), "addScript", "PassValues(" + locationName + ")", true);

在javascript中我的代码包含

<script language="javascript" type="text/javascript">
        function PassValues(locationName)
            {
             var txtValue = locationName; 
             alert(txtValue);
            }
</script>

这里的警报显示undefined而不是"Mumbai"

试着在后面的代码中给变量加上单引号。如果没有它们,浏览器会认为您传入了一个名为Mumbai的变量。你真正想传递的是字符串"Mumbai"。您将得到消息'undefined',因为在客户端代码中没有名为Mumbai的变量。

 string locationName = "Mumbai";
    Page.ClientScript.RegisterStartupScript(Type.GetType
    ("System.String"), "addScript", "PassValues('" + locationName + "')", true);

这对我来说是完美的:

Default.aspx.cs

using System;
using System.Web.UI;
namespace WebApplication2
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string locationName = "Mumbai";
            Page.ClientScript.RegisterStartupScript(Type.GetType("System.String"), "addScript", "PassValues('" + locationName + "')", true);
        }
    }
}

违约。aspx(当创建新的web应用程序用于测试时,从Visual Studio 2010自动生成作为内容页)

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script language="javascript" type="text/javascript">
    function PassValues(locationName) {
        var txtValue = locationName;
        alert(txtValue);
    }
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        Welcome to ASP.NET!
    </h2>
</asp:Content>

只是为了快速解决您的问题,您可以简单地使用内联ASP。. NET,以快速运行您的应用程序:

<script language="javascript" type="text/javascript">
        function PassValues(locationName)
        {
           var txtValue = locationName; 
           alert(txtValue);
        }
        PassValues('<%= locationName %>');
</script>
但是,问题是,您的代码在浏览器中呈现为:
PassValues(Mumbai);

这意味着JavaScript试图找到一个名为Mumbai的变量,由于它找不到它,因此将显示undefined消息。因此,您应该将代码更正为:

"PassValues('" + locationName + "')"

需要引用参数

改变:

"PassValues(" + locationName + ")" 

"PassValues('" + locationName + "')"

您错过了在PassValues javascript函数中作为字符串传递的引号

 string locationName = "Mumbai";
    Page.ClientScript.RegisterStartupScript(Type.GetType
    ("System.String"), "addScript", "PassValues('" + locationName + "')", true);