How do I redirect? - c#

I have an image that is a hyperlink. How do I access my "searchRedirect" function for a redirect from the server side after the image is clicked?
<input id="textSearch" runat="server" name="textSearch" type="text" />
<asp:HyperLink id="searchButton" runat="server">
<img alt="" src="images/SearchButton.png"/>
</asp:HyperLink>
protected void searchRedirect()
{
Response.Redirect("/NewProject/Home/?searchString=" + textSearch.Value;
}

Rather than a HyperLink, you'll want to use a LinkButton and listen for its Click event
<input id="textSearch" runat="server" name="textSearch" type="text" />
<asp:LinkButton id="searchButton" runat="server" OnClick="searchRedirect">
<img alt="" src="images/SearchButton.png"/>
</asp:LinkButton>
protected void searchRedirect(sender As Object, e As EventArgs)
{
Response.Redirect("/NewProject/Home/?searchString=" + textSearch.Value);
}
Al Kepp is suggesting that doing it this way causes the page to post back only to realize the redirect, leading to an unnecessary page load. A javascript version such as the one below would avoid the first post back:
<input id="textSearch" runat="server" name="textSearch" type="text" />
<a href="#" onclick="window.location='/NewProject/Home/?searchString=' + getElementById('textSearch').value; return false;">
<img alt="" src="images/SearchButton.png"/>
</a>
I didn't actually test that code, but I don't think I have any typos.

Either write it in JavaScript, because it is the only way how to perform that code on client side. That is necessary to make it work exactly as you wish.
Or use LinkButton as Nick Spiers said. In that case you won't see testSearch.Value in url address. (That is often good, but if you want to see it there, the best you can do is to write it in JavaScript.) But unlike Nick Spier's code, I would omit redirect command there and perform the required search action immediately. (Because redirect will cause sending two pages to client, which is not what user usually expects when he/she presses the search button.)

Or you could use javascript and get rid of an extra roundtrip to the server. Here's an example using jQuery
<input id="textSearch" class="textSeachClass" runat="server" name="textSearch" type="text" />
<asp:HyperLink id="searchButton" CssClass="searchButtonClass" runat="server">
<img alt="" src="images/SearchButton.png"/>
</asp:HyperLink>
<script type="text/javascript">
// This code should be put in a separate .js-file so it can
// be cached and the aspx page will be more SEO-friendly
$("a.searchButtonClass").click(function (e) {
e.preventDefault();
window.location = "/NewProject/Home/?searchString=" + $("input.textSeachClass").val();
});
</script>
I use css classes as selectors since ASP.Net Webforms will change the client id of the controls when they get rendered, unless you use .Net Framework 4.

Related

How to track asp:button click with Google Tag Manager

Let's say I've got an asp:button on a website which I'm trying to track to count how many times it has been clicked by different users.
<asp:Button ID="SubBtn" runat="server" OnClick="Button1_Click" runat="server" Text="Sub" />
In my code behind I've got a redirect link to a different page.
I'm aware that I need to include something like
<a href="#" name="button1" onclick="dataLayer.push({'event': 'button1-click'});" >Button 1</a>
Do I need to convert my asp:button to a html button to make this work?
You need to use attribute "OnClientClick":
<asp:Button ID="SubBtn" runat="server" OnClick="Button1_Click" runat="server" Text="Sub" OnClientClick="dataLayer.push({'event': 'button1-click'});" />
You can read more about this attribute on MSDN: https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick(v=vs.110).aspx

Solution for use <% ... %> where runat="server" (or vice versa) in asp.net

My idea
When the user click on the a tag with his avatar, he must redirect to another page. I do this with the code by number one (see below).
<div>
<!--show new messages | only show when log in. -->
<a href="<%=ResolveUrl("~/messages/inbox.aspx") %>" class="click headeritem" id="messages">
<img src="<%=ResolveUrl("~/images/message.png") %>" alt="new messages" id="messages" />
<asp:Label class="number" id="lblNewMessages" runat="server">1</asp:Label>
</a>
<!--log in | only show when log out. -->
<div class="user" id="logOut" runat="server">
Log in
Regist
</div>
<!--go to the profile of the user | only show when log in. -->
<!--1-->
<a class="click user" id="logIn" href="<%=ResolveUrl("~/gebruiker.aspx") %>">
<img id="picture" src="<%=ResolveUrl("~/afbeeldingen/person-male.png") %>" alt="user" />
<asp:Label runat="server" id="points" class="points">10</asp:Label>
</a>
</div>
With this C# code I place some tags invisible dependent on log in or out.
if (Request.Cookies["user"] != null) // log in
{
FindControl("logOut").Visible = false; // 2
}
else // log out
{
FindControl("logIn").Visible = false; // 2
FindControl("messages").Visible = false;
}
Extra information about the code: If you are login, I place a cookie with the user's id. If the cookie is not null, the user is login, other ways not. If you are login, it place the a-tag with id logout unvisible.
My problem
Now this code will give a NullReferenceException on line two.
Additional information: Object reference not set to an instance of an object.
If I place runat="server" to the a-tags, it give me this:
Server Labels should not contain <% ... %>-constructs.
There is an <% ... %>-constructor added on the a-tag in the code above for get the correct url to go to the correct page.
This is my problem. You can not add a <% ... %>-constructor where runat="server" stand. How can you do it on a correct way?
Other information
Maybe also important to know is that my project has sub directories. It must be important to go from messages/inbox.aspx to user/profile.aspx for eg.
All this code above is added to a master page that I use for all the pages.
Can anyone help me? Thanks and sorry for my poor English.
Instead of using plain a-tags, you could use WebForm-controls like Panels or Hyperlinks, e.g.:
<!--log in | only show when log out. -->
<asp:Panel CssClass="user" id="logOut" runat="server">
<asp:HyperLink NavigateUrl="~/gebruikers/aanmelden.aspx" CssClass="click" id="logIn" Text="Log in" runat="server" />
<asp:HyperLink NavigateUrl="~/gebruikers/registreren.aspx" CssClass="click" id="regist" style="left:100px" Text="Regist" runat="server"/>
</asp:Panel>
This might reduce the amount of control you have over the generated HTML (so you'd have to check whether the HTML is good for you), but would enable you to access the controls in Code behind more easily, e.g.:
if (Request.Cookies["user"] != null) // log in
{
logOut.Visible = false; // 2
}
else // log out
{
logIn.Visible = false; // 2
messages.Visible = false;
}
There are a few different varieties of ASP.net inline tags. Please see the full list here: https://support.microsoft.com/en-us/kb/976112
Not all of them support placement inside the attributes of a server-side control's tag. The <%# ... %> data-binding expression inline format would allow you to do that, and I think the older <% ... %> format also. The <%= ... %> inline tag will definitely not work inside the server-side control tag because the whole expression is directly compiled instead of displaying the content as an attribute value.
If your main goal is controlling visibility of a server-side control, then you should just be able to set control.Visible = false; in your code-behind. If you'd like to control visibility of a non-server-side control (or a block of controls), then the <asp:Panel> server-side control might be your best route. ASP.net has tried to move away from the excessive inlining approach of the old ASP.
I used to get errors similar to the one you specified. Because the ResolveUrl uses "", avoid using that for the HREF attribute too as it might break the code. Try the below code:
<a href='<%=ResolveUrl("~/messages/inbox.aspx") %>' class="click headeritem" id="messages">
<img src="<%=ResolveUrl("~/images/message.png") %>" alt="new messages" id="messages" />
<asp:Label class="number" id="lblNewMessages" runat="server">1</asp:Label>
</a>

HTML tag:label with onclick asp.net method.

I have this form:
<form id="form21" runat="server" method="post" onsubmit="return send()">
<asp:Button runat="server" ID="submit" name="submit" type="submit" class="btn btn-send" Text="עדכן" onclick="submit_Click" />
<label ID="other" name="other" runat="server" class="btn btn-send" onclick="other_Click" Visible="False">נהל משתמש אחר</label>
</form>
When I click on the label this error occur: "JavaScript runtime error: 'other_Click' is undefined".
How can I combine between asp.net method and HTML tag?
From server perspective, this:
<label ID="other" name="other" runat="server" ...
is an instance of HtmlGenericControl class. This class and most of its subclasses does not have server-side click event. So the onclick you defined is not treated as server-side subscription and therefore rendered into the HTML as is. So on the final page is this just a JavaScript function call. And since you do not have such function on the client side, you get the error.
To resolve it you might want to switch to some sever-side control which has serve-side Click event. For example LinkButton, though it will require some css to look like label. Other option is to generate postback yourself on the client, but this is a bit unusual path.
you should define what do you want to do, the click is for show or execute one task or do you want execute to the server side..
For execute one task with the click and not call to the server, you should define the function javascript and call
For execute call to the server with the event click , you should use wcf ajax for call the server..
or maybe this can help you
http://www.morgantechspace.com/2014/01/Call-Server-Side-function-from-JavaScript-in-ASP-NET.html

Show User Control through Static Method

I have been researching this, but haven't been able to find anything so far.
Currently, I am using a Javascript alert box on my ASP page:
public static class Alert
{
public static void Show(string message)
{
string script = "<script type=\"text/javascript\">alert('" + message + "');</script>";
Page page = HttpContext.Current.CurrentHandler as Page;
if (!page.ClientScript.IsStartupScriptRegistered("alert"))
{
page.ClientScript.RegisterStartupScript(typeof(Alert), "alert", script);
}
}
}
I am able to call this from code behind by: Alert.Show("Text");
My plan is to replace the Javascript alert by utilizing the AjaxControlToolkit's ModalPopupExtender. I am creating a user control that looks something like this:
<ajax:ModalPopupExtender ID="mpAlert" runat="server" PopupControlID=""
TargetControlID="btnExport" OkControlID="btnOK">
</ajax:ModalPopupExtender>
<asp:Panel ID="pnlSteps" runat="server" BackColor="#C5D9FC" Width="10%"
BorderColor="#093E9A" BorderStyle="Double" BorderWidth="5px"
style="border-radius: 10px; padding: 5px;">
<div>
<asp:Literal ID="lSteps" runat="server" />
</div>
<div>
<input id="btnOK" type="button" value="OK" />
</div>
</asp:Panel>
I am wondering if there is a way I can create a static method to show this from codebehind, similar to how I used the Javascript alert. I'd like to be able to wrap this in a class so I could just call AjaxAlert.Show(), without having to call anything in the aspx file.
This is still a rough idea, so if any more details are needed, just let me know.
You can show the ModalPopupExtender from codebehind. Therefore you need an invisible trigger button.
mpAlert.Show();
So set the TargetControlID of the ModalPopupExtender to a hidden button:
<asp:Button ID="Hid_ShowDialog" Style="display: none" runat="server" />

Scroll down to the specific part of page when a linkbutton is clicked using MaintainScrollPositionOnPostBack

I have a lengthy asp.net page. An HTML table in the page has a link with <a>. when the link is clicked the page shows the textbox using javascript and takes me to the top part of the page. Instead, i want to see the part of the page that has the link and textbox. It should automatically scroll down to that part once the page refreshes. How is that possible?
I have tried using Linkbutton instead of but have issues with javascript.
Here is the code.
<script type="text/javascript">
$(document).ready(
function()
{
$("#aChangeDefault").click
(
function()
{
alert('hi');
//$("#<%=trChangeLoc.ClientID %>").fadeIn(1000);
$("#<%=rowChangeLoc.ClientID %>").fadeIn(1000);
}
)
$("#btnClose").click
(
function()
{
$("#<%=rowChangeLoc.ClientID %>").fadeOut(1000);
if(document.getElementById("<%=divSearchResult.ClientID %>").style.display != "none")
{
$("#<%=divSearchResult.ClientID %>").fadeOut(1000);
}
//$("#<%=trChangeLoc.ClientID %>").fadeOut(10);
}
)
}
);
The Linkbutton is here :
<asp:LinkButton id="aChangeDefault" runat="server" style="font-size: 12px;font-family:Arial;vertical-align:bottom;" ToolTip = "Click here to set your town as default location" Text ="Change Location" > </asp:LinkButton>
And the portion that shows up when the link is clicked is here:
<input id="btnClose" type="button" class="closeButton2" language="javascript" onclick="return btnClose_onclick()" />
<div style="display: inline-block;">
<span class="searchheadder" style="color: #000000; padding-right: 8px; padding-top: 4px;">
LOCATION: </span>
<asp:TextBox ID="txtChangedLocation" onkeyup="doCapitalize();" runat="server" Height="19px"
Width="200px" CssClass="textBox" Style="margin-right: 10px;"></asp:TextBox>
<cc1:AutoCompleteExtender ID="ACE1" runat="server" TargetControlID="txtChangedLocation" ServicePath="../AutoComplete.asmx" ServiceMethod="GetCompletionList" MinimumPrefixLength="2" CompletionSetCount="10" EnableCaching="true" CompletionInterval="0" ></cc1:AutoCompleteExtender>
<asp:Button ID="btnGetNewList" BorderWidth="0" CssClass="searchButton" runat="server" OnClick="btnGetNewList_Click" /> </div>
Appreciate all your help. Thank you!
MaintainScrollPositionOnPostBack only affects the position of the page in your browser when a PostBack occurs, and if you're using JavaScript you don't want a PostBack to happen. If you're doing everything in JavaScript, it sounds like the problem is that when you click a link, the browser's default behavior is to follow the link, even if it's to a location on the same page. In some browsers, for the click event to register on an <a> tag, the href property must have a value, so it's common practice to use a blank anchor name as the href:
<a onClick="MyJavaScriptFunction()" href="#">Click here</a>
What this is actually telling the browser to do is to call your function MyJavaScriptFunction() and unless that function evaluates to false, it will then follow the anchor to the top of the page, which is where href="#" takes you. You can either finish your onClick with return false; or else change your JavaScript function to always return false, either way it will keep the browser from following the link:
<a onClick="MyJavaScriptFunction();return false;" href="#">Click here</a>
I'm not sure I understand what you're trying to do, but if the page is reloading perhaps you can use a named anchor to have the browser go to the section of the page you want automatically.

Categories