Open asp LinkButton in a new tab - c#

I have a button in my gridview and when the users click on it, it goes to the page. However, if you right click on it and "open link in a new tab" it goes to a blank page. I want it so when the user right click on it and "open link in a new tab" to go to the page. This is the code that I have so far:
aspx
<asp:LinkButton ID="lnkEditbtn" data-toggle="tooltip" title="View Request" OnClick="lnkEditbtn_Click" runat="server" class="btn btn-primary btn-sm" Text="<%# bind('ticketID')%>"></asp:LinkButton>
c#
protected void lnkEditbtn_Click(object sender, EventArgs e)
{
GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);
Label lblid = (Label)gvr.FindControl("lblMovie");
int id = Convert.ToInt32(lblid.Text.ToString());
SecureQueryString qs = new SecureQueryString();
qs["ID"] = id.ToString();
Response.Redirect("viewMovie.aspx?qs=" + qs.ToString());
}

you cannot do this with linkbutton because it redirects to the desired view after you click on it but you can use asp:HyperLink and set its value like
<asp:HyperLink ID="lnkEditbtn" data-toggle="tooltip" Text="View Request" runat="server" NavigateUrl='<%# Eval("ticketID", "~/viewMovie.aspx?qs={0}") %>' class="btn btn-primary btn-sm" ></asp:HyperLink >
Edit
if you want the URL to be encrypted first create a class
public static class encrypt
{
public static string encvalue(int id)
{
SecureQueryString qs = new SecureQueryString();
qs["ID"] = id.ToString();
return qs.ToString()
}
}
and your hyperlink will be
<asp:HyperLink ID="lnkEditbtn" data-toggle="tooltip" Text="View Request" runat="server" NavigateUrl='<%# String.Format("~/viewMovie.aspx?qs={0}",encrypt.encvalue(Convert.ToInt32(Eval("ticketID")))) %>' class="btn btn-primary btn-sm" ></asp:HyperLink >

Link button in server side gets rendered to Hyperlink in client side with 'href' as href="javascript:__doPostBack('lnkEditbtn',''), which is nothing but a postback to the server from the link button. So when you right click and open the link in a new tab, it posts to the server and hence it comes up as blank page in new tab.
What you can do is use code similar to the below code:
<style>
.hide {
display:none;
}
</style>
<script>
function postBack() {
__doPostBack('lnkEditbtn', '');
return false;
}
</script>
<asp:LinkButton ID="lnkEditbtn" runat="server" OnClick="lnkEditbtn_Click" Text="Link" CssClass="hide"></asp:LinkButton>
Link
protected void lnkEditbtn_Click(object sender, EventArgs e)
{
var linkButton = (Control)sender as LinkButton;
}
With this code, you are hiding the link button and using the Anchor tag instead.
Href in Anchor tag will be invoked when you right click. And when you click the link, "postBack" JS method will be triggered that invokes the server side event handler for the Link Button.
And there by both right click and left click works.

Related

Cannot get Button to activate code behind in ASP.NET / C#

I am unable to get my button to activate my code behind. I have tried adding asp-source, asp-action, runat, and every time my onclick does not work and I get the error:
47 Uncaught ReferenceError: PlayerHit is not defined
at HTMLUnknownElement.onclick
This is my markup:
<asp:Button runat= "server" id="butAddPlayerCard" onclick="PlayerHit">Hit2</asp:Button>
<button onclick="PlayerHit" id="finalButton" runar>Final</button>
<button ID="Button2" onclick="PlayerHit" runat="server" Class="btn btn-primary btn-light">Hit</button>
I just need one button but this is to show what I have tried.
Code behind:
public void PlayerHit(object sender, EventArgs e)
{
DeckAction deckAction = new DeckAction();
deckAction.AddCard(deck, PlayersHand);
foreach (var item in PlayersHand)
{
if ((item.Values) == 0)
{
var cardValue = item.Values;
}
}
}
This code is in the main class of the file.
According to Button.OnClick method, it should be OnClick but not onclick. And use the Web form control.
<asp:Button ID="Button2" OnClick="PlayerHit" runat="server"
Class="btn btn-primary btn-light">Hit</asp:Button>

Show/Hide href link on click on a button

On a BUTTON click a detail page is generated.
I have a href link when click on it, it navigates in the page.
But on page load there should be only the button (on Clicking it main page is generated) but the href link is also appearing.
I want on the page load there should be only one button by clicking on it href link should appear.
And should disappear when another button is clicked.
Scrip:
$(document).ready(function () {
$('#priorityC').hide();
$('#perC').hide();
});
$('#btnAnalyse').click(function () {
$('#priorityC').show();
$('#perC').show();
});
This is the button:
<asp:ImageButton ID="btnAnalyse" runat="server" OnClick="btnAnalyse_Click"/>
This is the href link which i want to show only on the click of the above button:
Hourly Detailed Priority Representation
<a name="priorityPer">
<div id="perC" class="center">
<asp:Label ID="lblDPTC" runat="server" Text="Detailed Percentage representation of Ticket Count" Visible="false"></asp:Label>
</div>
</a>
Its hiding on page load but not showing on button click.
<asp:ImageButton ID="btnAnalyse" runat="server" ImageUrl="image1.jpg" OnClick="btnAnalyse_Click"/>
Hourly Detailed Priority Representation
<a name="priorityPer">
<div id="per" class="center">
<asp:Label ID="lblDPTC" runat="server" Text="Detailed Percentage representation of Ticket Count" Visible="false"></asp:Label>
</div>
</a>
and on your backend page( codepage.cs)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
linkid.Visible = false;
}
}
protected void btnAnalyse_Click(object sender, ImageClickEventArgs e)
{
if (linkid.Visible == false)
{
linkid.Visible = true;
}
}
protected void btnAnother_Click(object sender, EventArgs e)
{
linkid.Visible = false;
}
You can write your href link inside a div and using Jquery, you can hide and show the the div accordingly.
Code snippet
<script>
// On load hide the div
$(document).ready(function(){
$('#MYDIV').hide();
};
// call this function on button click to show/hide the link
function showHideLink(buttonName)
{
if(buttonName=='blah')
{
$('#MYDIV').hide();
}
else
{
$('#MYDIV').show();
}
}
</script>
Hope this helps.
test.aspx
<li class="nav-item">
<a class="nav-link" id="AdminFaciliy" href="charts.html" runat="server">
<i class="fas fa-fw fa-user">
</i>
text.aspx.cs
if (Utype.Trim().ToUpper()=="ADMIN"){
AdminFaciliy.Visible = true;
}

Why using IHttpHandler causes my submit button to open to the new window

<asp:Panel ID="pnlSearch" runat="server" DefaultButton="btnValidateName">
<div class="spPad">
<b class="userLabel">Enter Full/Partial First or Last Name to Search (Leave blank for all):</b>
</div>
<div class="spPad" style="text-align: right;">
<asp:TextBox ID="txtName" Width="95%" runat="server" ClientIDMode="Static"></asp:TextBox>
</div>
<div class="spPad" style="text-align: right;">
<asp:Button ID="btnValidateName" CssClass="orange button" runat="server" Text="Validate Name" onclick="btnValidateName_Click" />
</div>
<div class="spPad" style="text-align: right;">
<asp:Label runat="server" Text="" ID="lblIsValid"></asp:Label>
</div>
</asp:Panel>
After searching and displaying the result inside a repeater, I allow user to view the file in the browser by opening a new window by clicking on a linkbutton:
<asp:LinkButton ID="lnkView" Text="View in Browser" OnClientClick="window.document.forms[0].target='blank';" runat="server" OnClick="ViewFile" />
The code behind is this:
protected void ViewFile(object sender, EventArgs e)
{
Response.Redirect("OpenFilePDF.ashx?fileVar=" + Session["fileName"]);
}
The OpenFilePDF.ashx code is:
public void ProcessRequest (HttpContext context) {
System.Web.HttpRequest request2 = System.Web.HttpContext.Current.Request;
string strSessVar2 = request2.QueryString["fileVar"];
try
{
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/pdf";
byte[] fileByteArray = File.ReadAllBytes(Path.Combine(#"C:\PDF", strSessVar2));
response.AddHeader("Content-disposition", String.Format("inline; filename={0}", strSessVar2));
response.BinaryWrite(fileByteArray);
response.End();
}
catch (Exception ce)
{
}
}
public bool IsReusable {
get {
return false;
}
}
The scenario that is happening is, after the search and displaying the result, if the user clicks on the View in Browser button and comes back to the old window and clicks on the Validate Name button the result goes in the window that was originally opened by clicking on View in Browser button instead of running the search on the current window. I have to refresh the page for it to search on the current window again, even if the new window was already opened.
How do I resolve the issue I am having?
Your View in Browser is implemented as
<asp:LinkButton ID="lnkView" Text="View in Browser" OnClientClick="window.document.forms[0].target='blank';" runat="server" OnClick="ViewFile" />
On the client click, the form element of your web page will look like
<form ... target="_blank">
Causing any submit of the form to open in a new window. However, every single postback to ASP.NET constitutes a submission of your form, so everything will open in a new window. Rather than setting the target attribute on the form, you might consider setting the attribute just on the link. To do that, see this answer:
https://stackoverflow.com/a/2637208/1981387
Keep in mind, you will have to use a HyperLink instead of a LinkButton. Actually, this will benefit you by reducing the round trip back to your server by 1, because you are using the LinkButton to redirect to another url anyways. So your HyperLink can just have an href that points to "OpenFilePDF.ashx?fileVar=" + Session["fileName"] to begin with.
Edit/TL;DR:
Change
<asp:LinkButton ID="lnkView" Text="View in Browser" OnClientClick="window.document.forms[0].target='blank';" runat="server" OnClick="ViewFile" />
To
code-behind:
public string FileLocation
{
get
{
return "OpenFilePDF.ashx?fileVar=" + Session["fileName"];
}
}
protected void Page_Load(object sender, EventArgs e)
{
...
lnkViewProper.NavigateUrl = FileLocation;
...
}
markup:
<asp:HyperLink
ID="lnkViewProper"
Text="View in Browser"
runat="server"
Target="_blank" />

How to keep jquery modal open after postback?

I am having an empty div and i am using LOAD method of jquery and getting data from another aspx page. it works fine. it gets File upload and button control from that page. now when i click on the button my button code doesn't get called and my dialog gets close.
jQuery On Page1.aspx
var checkP = $('#<%= productName.ClientID %>').val();
checkP = checkP.replace(/\ /g, '-');
$("#midDiv").load("UploadImages.aspx?prodName=" + checkP + " #midDiv");
$("#midDiv").dialog();
//It Shows Dialog With File Upload Option & Button Option.
Page1.aspx
<div id="midDiv">
</div>
Page2.aspx
<div id="midDiv">
<asp:FileUpload ID="productsImages" CssClass="hid" runat="server" />
<asp:Button ID="Button1" runat="server" OnClick="uploadImageTemp" Text="Button" />
</div>
Page2.aspx.cs //Code Behind
protected void uploadImageTemp(object sender, EventArgs e)
{
//Some Work Here...
}
Is there any way that my button code gets called or is there any way to keep jQuery modal open ?
Append your dialog in form like below.
var checkP = $('#<%= productName.ClientID %>').val();
checkP = checkP.replace(/\ /g, '-');
$("#midDiv").load("UploadImages.aspx?prodName=" + checkP + " #midDiv");
$("#midDiv").dialog().parent().appendTo($("form:first"));
Change your button control to link button control.
<div id="midDiv">
<asp:FileUpload ID="productsImages" CssClass="hid" runat="server" />
<asp:LinkButton ID="Button1" runat="server" OnClick="uploadImageTemp" Text="Button" />
</div>
Now call your code behind button click event.

C# Repeater dynamic Button

I am using repeater to generate the button control.
<asp:Repeater ID="rptDoc" runat="server">
<ItemTemplate>
<div style="...">
<asp:Button ID="btnUpload" runat="server" Text="Button" OnClick="button_Click" />
</div>
</ItemTemplate>
</asp:Repeater>
For example, I can generate 4 buttons. However, how can I implement
the program inside each of the button?
when btnUpload1 clicked, it will upload files into Folder1,
when btnUpload2 clicked, it will upload files into Folder2
I know there is a way that create a Table in the web form, and then
dynamically put the generated button inside the table cells... But I
have lots of DIVs with styling, so I don't want to use a table to
place the dynamic buttons.
Thanks for help.
It works for me now, I used the LinkButton instead of Button.
Also added OnItemCommand="ItemCommand" in repeater.
And finally it will goto ItemCommand event when LinkButton clicked.
It gets the value from CommandArgument which set in dynamic LinkButton
<asp:Repeater ID="rpt" runat="server" OnItemCommand="ItemCommand">
<ItemTemplate>
<asp:LinkButton runat="server" CommandArgument='<%# Eval("lbtnUploadCommandArgument")%>' CommandName="ButtonEvent">Upload Files</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
protected void ItemCommand(Object Sender, RepeaterCommandEventArgs e)
{
string[] arr_Para = ((LinkButton)e.CommandSource).CommandArgument.Split(';');
}
When you dynamically add buttons to the web form, you can track what each button should be doing and then process that URL in a common click event, like the hackish example below.
Dictionary<System.Web.UI.WebControls.Button, string> ButtonToURIMap = new Dictionary<System.Web.UI.WebControls.Button, string>();
private void AddButtonToForm()
{
System.Web.UI.WebControls.Button myWebButton = new System.Web.UI.WebControls.Button();
//Initialize/Style your button here.
myWebButton.Click +=myWebButton_Click;
ButtonToURIMap.Add(myWebButton, "http://www.google.com/");
}
void myWebButton_Click(object sender, EventArgs e)
{
if (sender is System.Web.UI.WebControls.Button)
{
System.Web.UI.WebControls.Button callingButton = (System.Web.UI.WebControls.Button)sender;
if ( ButtonToURIMap.ContainsKey(callingButton))
{
string uri = ButtonToURIMap[callingButton];
//code you execute from here
}
}
}
All you need is below.
in your codebehind
Protected Sub MyPointsRepeater_RowCommand(sender As Object, e As System.Web.UI.WebControls.RepeaterCommandEventArgs) Handles MyPointRepeater.ItemCommand
arg = e.CommandArgument.ToString().Split(";"c)
End Sub
in your Aspx page
<asp:Repeater ID="MyPointRepeater" runat="server">
<ItemTemplate>
<label class="ConferenceName"><%#Eval("Conference Name").ToString()%></label><br />
<label class="RegistrationId"><%#Eval("CPD Points / Hours").Tostring() %></label>
<label class="Type"><%#Eval("Type").ToString()%></label>
<asp:LinkButton ID="lnkCustomize" Text="Download Certificate" CommandName="Customize" CssClass="fontLight"
CommandArgument='<%#Eval("R_Id").Tostring() + ";" + Eval("Conf_Id").Tostring() + ";" + Eval("Reg Id").Tostring() + ";" + Eval("CPD Points / Hours").Tostring() + ";" + Eval("Type").Tostring()%>' runat="server" />
</ItemTemplate>
</asp:Repeater>

Categories