Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

in javascript my code contains

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

Here the alert shows undefined instead of "Mumbai"

like image 902
Priscilla Jobin Avatar asked Feb 11 '26 09:02

Priscilla Jobin


2 Answers

Try putting single quotes around your variable in the code behind. Without them, the browser thinks you are passing in a variable named Mumbai. What you really want to pass is the string 'Mumbai'. You get the message, 'undefined', because there is no variable named Mumbai in the client side code.

 string locationName = "Mumbai";
    Page.ClientScript.RegisterStartupScript(Type.GetType
    ("System.String"), "addScript", "PassValues('" + locationName + "')", true);
like image 121
Bert Avatar answered Feb 13 '26 00:02

Bert


this works perfectly for me:

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 ( auto generated as content page from Visual Studio 2010 when created the new web application for testing )

<%@ 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>
like image 22
Davide Piras Avatar answered Feb 13 '26 02:02

Davide Piras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!