2011-11-16 101 views
2
string locationName = "Mumbai"; 
    Page.ClientScript.RegisterStartupScript(Type.GetType 
    ("System.String"), "addScript", "PassValues(" + locationName + ")", true); 

在JavaScript我的代碼包含警報顯示在JavaScript中未定義

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

這裏警報顯示不確定的,而不是「孟買」

+0

歡迎來到SO,請使用{}工具箱按鈕提到你的代碼部分。 –

回答

4

嘗試把單引號括起來你的代碼後面的變量。沒有它們,瀏覽器會認爲你傳入了一個名爲Mumbai的變量。你真正想要通過的是字符串「孟買」。您會收到'未定義'的消息,因爲在客戶端代碼中沒有名爲Mumbai的變量。

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

只是爲了迅速消除你的問題,你可以簡單地使用直列ASP.NET,快速運行應用程序:

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

但是,問題是,你的代碼在瀏覽器中呈現如:

PassValues(Mumbai); 

這意味着JavaScript嘗試找到一個名爲孟買變量,因爲我t不會找到它,則會顯示undefined消息。因此,你應該糾正你的代碼爲:

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

但仍然顯示undefined –

+0

然後,只需在方法「PassValues」的開頭放置一個'debugger;'行,然後在Firefox中調試JavaScript(使用Firebug)。 –

2

這個完美的作品對我來說:

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); 
     } 
    } 
} 

Default.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> 
+0

但仍然警報顯示未定義 –

1

您需要引用參數

變化:

"PassValues(" + locationName + ")" 

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

但仍然警報顯示未定義 –

+0

是否有一個原因爲什麼你明確將類型設置爲「System.String」類型? – simonlchilds

1

你錯過了報價傳遞的字符串在PassValues javascript函數

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

但仍然警告顯示undefined –

+0

請確保您的方法'PassValues'高於注入的JavaScript。 –