I am having links like:
<asp:HyperLink ID="lnkTitle" runat="server" CssClass="itemTitle" >
</asp:HyperLink>
<a id="linkOwner" runat="server" class="authorName"></a>
I am assigning the NavigateUrl from code behind at run time like:
lnkTitle.NavigateUrl = "MyPage.aspx?id=" + userID;
linkOwner.HRef= "MyPage.aspx?id=" + userID;
(where userID is an integer type variable)I need to access the id value from the navigate url in js file for both the cases. How access it by using jquery?Can anyone help me?
Two possible options
href
attribute of the generated link, and extract the userId from there : the code-behind you are typing will result in the generation of something like<a href="MyPage.aspx?id=1234" id="SomeCrazyIDGeneratedByASP.NET">text of the link</a>
the problem here, is that the ID of the generated link may vary ... which makes the link harder to find in the page using a jQuery selector. I would suggest adding a specific CSS class to your links, for instance user-page
. Then you could do something like this, I suppose :
/*extract the href attribute from the link, and get the item after the last "=" sign*/
var href = $('a.user-page').attr('href');
var split = href.split("=");
/*reverse it and take the first item (used to be last)*/
var userId = split.reverse()[0];
alert(userId);
The other option I usually prefer is to expose a server-side variable such as userId
directly in Javascript... In order to do that, you must make userId
visible from the .aspx file. Then in your .aspx file, do something like that
<script type="text/javascript">
var userId = <%=userId%>;
alert(userId);
</script>
Then you can use it as any javascript variable !