moondaddy
moondaddy

Reputation: 39

c# ASP.NET Webforms: Dynamically creating anchor elements with dynamic hrefs

I am using VS 2019, C# 4.8 and ASP.NET WebForms. I have a page that serves as a listing. Each row has a company name and when the user clicks on it, I want top another page and pass that company's Id in as a parameter. Or is there a better way to do this that's SEO friendly?

Below is a screenshot of my troubled code:

enter image description here

  1. As you can see, I'm trying to pass the company ID into the url as a parameter (itm.Co_Id) but this fails as shown in the next screenshot:

enter image description here

  1. If I put the row# and company name in the anchor tag's text area it won't compile as shown below:

enter image description here

What is the right way to do this?

Upvotes: 1

Views: 1005

Answers (1)

Albert D. Kallal
Albert D. Kallal

Reputation: 49039

Unless you are inside of a data bound control, then you can't use

'<% Public Method of form goes here %>'

The above will not work. You CAN use the above expression in markup and controls that are NOT server based (so, you could remove runat="Server".). So any server control?

Those <% %> expressions can't be used!

Of course if we are inside of say any databound control? Then sure, you can use the "#" sign that means "during" data binding.

So, if this is say in side of a listview/gridview/details view etc.? And that item is data bound?

Then you CAN use this format in your markup:

'<%# Eval("column name from data source") %>'

'<%# Eval("HotelName") %>'

'<%# Eval("itm.Co_ID") %>'

But above assumes that these controls are inside of a database control (gridview/listview etc.).

So, this would be legal assume that itm.Co_ID is a PUBLIC member of that web form.

<h2>'<%= itm.Co_ID %>'</h2>

In above, itm.Co_ID has to be a public method/function of that given web page.

However, if you try this, then it will NOT work:

<h2 id="mybigtitle" runat="server" >'<%= itm.Co_ID %>'</h2>

So such expressions ONLY work in non server controls (without runat="server').

However, we could execute a databind on "mybigtitle" in code, and thus we could use this:

<h2 id="mybigtitle" runat="server" >'<%# Eval("itm.Co_ID") %>'</h2>

But, in code behind we would then need a

 mybigitle.dataBind()

And item.Co_ID would have to be a resolvable variable, class or public method or function of that web page for this to work.

However, you might well be already inside of a listview or some data bound control that is creating and spitting out the data - without that markup or known what kind of object your posted markup is part of - then it not clear if you can use "#" for a data bind expression such as

'<%# Eval("legal function etc. goes here") %>'

Without knowing if your markup is the result of a databind(able) control, then we have to guess a bit here as to what will work, or not.

Upvotes: 1

Related Questions