0

This is probably super simple and I'm sorry if I seem totally stupid but...

I'm coding my first asp.net web page for a class and I'm used to PHP

in PHP when you create a variable in one block of code you can use it in all the others (as long as it has already be initialized)

Here is an example of what I mean:

<?php $myVariable = "Hello World!" ?>

(later on in the code:)

<?php echo $myVariable; ?>

and In PHP that will work fine

Now the equivilant in asp as I understand it is:

<% String myVariable = "Hello World!"; %>

But when I try to use it in another block of code, the variable myVariable is not accessible

Am I doing something wrong?

1
  • 1
    This is normal, expected behavior in ASP.NET. Commented Oct 22, 2012 at 0:28

1 Answer 1

3

The problem here is the scope of the variable. I would suggest you to go through this article at http://www.informit.com/articles/article.aspx?p=25467&seqNum=5

Update

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    string myVariable = "This is a variable";
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <%=myVariable %>
    </div>
    </form>
</body>
</html>
Sign up to request clarification or add additional context in comments.

4 Comments

So, I just have to use <script> ?
@Axschech That is the standard for all non-PHP web languages
But I would suggest to use code behind approach of asp.net rather than using the inline approach for better maintainability of code.
Thank you guys sorry I was a derp!

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.