Functions in asp.net

  • Thread starter Thread starter Simon
  • Start date Start date
S

Simon

In asp I have the code like this:

<%
sub createUrl(name,link,clas)
if clas=1 then
class="top"
else
class="left"
end if
url="<a class='"&class&"' href='"&link&"'>"&name&"</a>"
response.write url
end sub
%>
....
<tr><td><%=createUrl("page","page.asp",1)</td></tr>
<tr><td><%=createUrl("page1","page1.asp",2)</td></tr>
....

enywhere in page I need something I just call the sub or function with
<%Call sub or function%>.
I don't know how I can create the same in asp.net. I read one book but I
didn't found any example.

Can someone help me?

Thank you,
Simon
 
Of course you can! I have developed an example for you using the familiar
single-page approach. Although, the real power of .net lies in separating
your code and content... using what's called "code-behind" pages... but
that's a little more advanced.

Code sample shown below.

Key concepts:
1. Because you are asking for a return value, you would want to use a
function rather than a sub generally.

2. You must declare (dim) any variables that you are using in your function,
and specify their datatype. By default, "option explicit" is on, meaning
that you must declare all variables. I'm not going to go into the issue of
scope here, but keep in mind that a variable declared in your function is
only available from within the function. You should thoroughly understand
scope and the use of "Public/Private/Shared..." subs and functions, if you
are serious about using .NET.

3. You must put spaces between your concatenation operators - e.g. don't
smush all your code next to your & characters or it will throw an error.

4. You may NEVER use the word "class" as a variable. Class is a reserved
keyword. Recommend appending a three letter prefix to all variables
indicating the datatype. .NET is what's called a "strongly typed" language,
meaning you have to always make sure variables contain data of an
appropriate type.

5. The return line is what will be returned from the function call. This
could be a string, integer, array/collection, or any other type of object.

<CODE>
<%@ Page Language="vb" Debug="true" %>
<script runat="server">
function createUrl(strName,strLink,intClass)
dim strClass as string
dim strUrl as string
if intClass=1 then
strClass="top"
else
strClass="left"
end if

strUrl="<a class='" & strClass & "' href='" & strLink & "'>" & strName
& "</a>"
return strUrl
end function
</script>
<html>
<head>
</head>
<body>
<%=createUrl("MyLink","http://www.mylink.com",1)%>
</body>
</html>
</CODE>
 
Back
Top