0

I'm having difficulty transferring a c# variable to a javascript value in my aspx file. This is what I currently have:

LetsChat.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR.Hubs;

public class Default
{
    public string pass = "password";
}

namespace SignalRChat
{
    [HubName("myChatHub")]
    public class LetsChat : Hub
    {
        public void send(string message)
        {
            Clients.All.addMessage(message);
        }
    }
}

Chat.aspx

<script type="text/javascript">
    var pass = "<%=pass%>";
</script>

Why is it giving me the following compilation error?:

The name 'pass' does not exist in the current context

5
  • 1
    The aspx page does not inherit from the class Default. Commented Jul 17, 2013 at 20:37
  • 1
    Because it is inside of Default class? Commented Jul 17, 2013 at 20:37
  • what does your @Page directive at the top of the .aspx file look like? Commented Jul 17, 2013 at 20:38
  • <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Chat.aspx.cs" Inherits="SignalRChat.Chat" %> Commented Jul 17, 2013 at 20:44
  • Given the above @ Page directive add partial Chat class inheriting from Page (inside the SignalRChat namespace) and put your public string pass there. Commented Jul 17, 2013 at 20:52

1 Answer 1

4

The markup in chat.aspx can only see members of its own class -- normally that is the partial class that is contained in code-behind. So, you can't see the pass variable, but you could use:

var pass = "<%=new Default().pass%>";

Alternatively you could make pass a static variable:

public class Default
{
    public static string pass = "password";
}
Sign up to request clarification or add additional context in comments.

7 Comments

I get the following error message now - Member 'Default.pass' cannot be accessed with an instance reference; qualify it with a type name instead
@methuselah um ... do you also have a page named "Default"?
@McGarnagle The member variable pass is already static. Why the need for new? Shouldn't it be just Default.pass?
@methuselah because now it is not a static variable and you're accessing it using new Default().pass which is why it works.
@JayPatel I meant one or the other -- either make pass static or use new Default().pass.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.