Open Link in New Tab in ASP.NET - c#

I'm trying to use a Button to open a link in a new tab in ASP.NET. I'm trying the following but it isn't working:
<asp:Button ID="ReportButton" runat="server" CssClass="button" Font-Size="XX-Large" ForeColor="White" Text="Report" OnClick="ReportButton_Click" OnClientClick="form1.target='_blank';" />
In the code, ReportButton_Click is defined as follows:
protected void SkidPackReportButton_Click(object sender, EventArgs e)
{
GoToPage(LocationSkidPackReportPage);
}
and GoToPage is defined as follows:
bool GoToPage(string page)
{
try
{
Response.Redirect(page);
return true;
}
catch (Exception)
{
StatusLabel.Text = "There was an error finding the page.";
return false;
}
}

Don't do server-side Response.Redirect, just do a client-side window.open. E.g.
void GoToPage(string page) {
ScriptManager.RegisterStartUpScript(this, this.GetType(), "newPage", String.Format("window.open({0});", page), True);
}
Or better yet - avoid postback altogether. You can assign clientClick to your button like:
ReportButton.OnClientClick = String.Format("window.open({0});return false;", LocationSkidPackReportPage);
This way new page will be opened on client without need to go back to the server.

Make LocationSkidPackReportPage a public property in code behind and then replace your button by:
Report
OR, if you need to fill this var in code behind:
// Response.Redirect(page); -> Replace this by:
string script = String.Format("window.open('{0}', '_blank');", LocationSkidPackReportPage);
ScriptManager.RegisterStartUpScript(this, this.GetType(), "reportResultPage", script, True);

this work for me
Page.ClientScript.RegisterStartupScript(
this.GetType(), "OpenWindow", "window.open('../_Reportes/ReporteGeneral.aspx','_newtab');", true);

Related

Separate button triggers "Please fill out this field"

I am building a web app with C# and asp.net. In the webpage, there is a header with a search bar and a body with a form. When I enter something in the search bar, one of the form fields shows the pop-up, "Please fill out this field".
This field is required, but for the form which has a separate submit button. So what I'm saying is my search button and form are connected but they shouldn't be.
Edit:
Code behind for the search button:
protected void btnOpenModalSearch(object sender, EventArgs e) {
//get information from database to populate the modal box with
PopulateModalBoxGridView();
ScriptManager.RegisterStartupScript(this, this.GetType(), "Properties",
\ "openModal();", true);
}
protected void PopulateModalBoxGridView() {
if (dtSearch == null) return;
//sort the search results in data table
DataView dvSearch = dtSearch.DefaultView;
dvSearch.Sort = SortOrder;
gridSearchResults.DataSource = dvSearch;
gridSearchResults.DataBind();
}
Code behind for the separate form:
protected async void btnCreateNewAsset_Clicked(object objSender, EventArgs evntArgs) {
//create a new asset
//first check for duplicates
if (IsDuplicateAsset()) { return; }
Asset newAsset = new Asset {
//creating asset
};
//post the asset to Team Dynamix
var addAssetUri = new Uri(locationOrigin + webApiBasePath + addAssetPath);
responseMsg = await httpClient.PostAsJsonAsync(addAssetUri, newAsset);
httpResponse = responseMsg.Content.ReadAsStringAsync().Result;
if (!responseMsg.IsSuccessStatusCode) {
Notification.Show(this, "Error. Response content=" + httpResponse, Status.Error);
}
else {
Notification.Show(this, "Successfully Created Asset.", Status.Success);
assetDictionary.Add(serialNumber.Text, serialNumber.Text);
ClearTextFields(frmIndex);
}
}
I found the answer here: HTML 5 required validator triggers on all buttons on the form
To save you the trip, I needed to add formnovalidate="formnovalidate" to my button
<asp:ImageButton ID="BtnSearch" formnovalidate="formnovalidate" data-target="#myModal" ClientIDMode="Static" runat="server" ImageUrl="~/images/search.svg" Text="Search" OnClick="btnOpenModalSearch"></asp:ImageButton>

c# Retrieve event from HTML code set in control placeholder

I'm doing a C# 3-tier project about pets
On load of the first webform I make a query to the database and get the data of all pets (id, name, photo) as a List to be shown as cards with images in HTML, I'm using Materialize by the way, I leave this link as example http://materializecss.com/cards.html
My code behind (Pets.aspx.cs) is this
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
NegPet negPet = new NegPet();
StringBuilder sbHtml = new StringBuilder();
List<EntPet> listEntPet = negPet.getAllPet(5); //5 is the user code (get all pets from user 5)
if (listEntPet.Count > 0)
{
foreach (EntPet entPet in listEntPet)
{
sbHtml.Append("<div class=\"col s6 m4\">");
sbHtml.Append("<div class=\"card\">");
sbHtml.Append("<div class=\"card-image\">");
sbHtml.Append("<img src=\"http://www.dogzone.com/images/breeds/beagle.jpg\" alt=\"\" class=\"circle responsive-img\" />");
sbHtml.Append("<asp:LinkButton id=\"lb_"+ entPet.Id_pet + "\" runat=\"server\" CommandArgument='<%# Eval(\""+ entPet.Id_pet + "\") %>')");
sbHtml.Append("\" click=\"updatePet_Click\" class=\"btn-floating halfway-fab waves-effect waves-light red\"><i class=\"material-icons\">edit</i></a>");
sbHtml.Append("</div>");
sbHtml.Append("<div class=\"card-content\">");
sbHtml.Append("<span class=\"card-title\">");
sbHtml.Append(entPet.Name_pet);
sbHtml.Append("</span>");
sbHtml.Append("</div>");
sbHtml.Append("</div>");
sbHtml.Append("</div>");
}
} else
{
sbHtml.Append("<h2>No pets found</h2>");
}
galPet.Controls.Add(new Literal { Text = sbHtml.ToString() });
}
}
Where galPet is a
<asp:PlaceHolder ID="galPet" runat="server" />
This code returns me all the "Id" and "Name" of "Pets" and sets it in the HTML design that I want, similar to a gallery. The problem comes when I try to get to the event onClick="updatePet_Click" apparently it never reaches it's method behind
public void updatePet_Click(Object sender, EventArgs e)
{
LinkButton btn = (LinkButton)(sender);
string yourValue = btn.CommandArgument.Substring(3);
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + yourValue + "');", true);
}
What I'm trying to do with this code is retrieve the ID from the clicked asp:LinkButton so I can use it in code behind
I also tried changing the event to "OnClick" but I got this error when tried to click it
Pets.aspx:24 Uncaught ReferenceError: updatePet_Click is not defined
at HTMLUnknownElement.onclick (Pet.aspx:24)
I would like to know how to retrieve the ID to work it in the code behind or if there is another way to pass my list to the HTML design where I can get the clicked ID easier. Thanks

Telerik window automatically opens after every page refresh

I am using Telerik RadControls in my project and and have a menu where I have an 'About' button. When I click the 'About' button a window pops up describing the application. The problem is if I refresh the page or navigate to another page then back to the first page the window automatically pops up.
The goal is only have that window pop up when the user clicks the about button.
here is the code I used to get that window:
<!--About Window-->
<telerik:RadWindowManager runat="server" EnableViewState="false" KeepInScreenBounds="true"></telerik:RadWindowManager>
<telerik:RadWindow ID="AboutMenu" Behaviors="Close" Animation="None" runat="server" Width="360px" KeepInScreenBounds="true" Height="360px" Modal="true" VisibleStatusbar="false" Skin="Glow">
<ContentTemplate>
<p style="text-align: center;">Sample Window Information</p>
</ContentTemplate>
</telerik:RadWindow>
Javascript
function OnClientItemClick(sender, eventArgs) {
if (window.args.get_item().get_text() == "About") {
var radwindow = window.$find(window.AboutMenu.ClientID);
window.args.set_cancel(true);
}
}
.cs
protected void MainMenu_OnItemClick(object sender, RadMenuEventArgs e)
{
if (e.Item.Text == "About")
{
AboutMenu.VisibleOnPageLoad = true;
}
}
The window works but it loads whenever the page loads and thats where I think the line AboutMenu.VisibleOnPageLoad = true comes into play and is causing the error but when I take out that line it won't display at all.
Instead of using VisibleOnPageLoad try using the following code to open the window on itemclick.
protected void MainMenu_OnItemClick(object sender, RadMenuEventArgs e)
{
if (e.Item.Text == "About")
{
string script = "function f(){$find(\"" + RadWindow1.ClientID + "\").show(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, true);
}
}
Or, just use the OnCLientItemClicking event of the menu to open the RadWindow and cancel the postback. But you will need to fix you JS code, because the arguements are in the context of the current function. ALso, the reference to RW may break unless you have made your own array of ClientIDs.
function OnClientItemClicking(sender, eventArgs) {
if (eventArgs.get_item().get_text() == "About") {
var radwindow = window.$find(<%=AboutMenu.ClientID%>);
radwindow.show();
eventArgs.set_cancel(true);
}
}

opening a radwindow from a user control

How to open a radwindow on the click event of a Imagebutton within a user control?
Moreover i have used the same code in aspx page and it works fine.
car.ascx
code behind car.ascx.cs
protected void btnCarLogo_Click(object sender, ImageClickEventArgs e)
{
carurl="https://www.google.co.in/"
ScriptManager.RegisterStartupScript(this, this.GetType(), "popCarWindow", "window.radopen('" + carurl + "', 'CarDetails');", true);
}
It has VisibleOnPageLoad property. If you set it to true, window will be visible after postback.
Examples:
Show window
myRadWindow.VisibleOnPageLoad = true;
Hide window
myRadWindow.VisibleOnPageLoad = false;
Take a look here: http://www.telerik.com/community/forums/aspnet-ajax/window/opening-radwindow-from-the-server.aspx and see that the parameters are Page and not this (i.e. UserCOntrol).
Here is on working with JS functio nnames in user controls: http://www.telerik.com/support/kb/aspnet-ajax/general/using-dynamic-unique-names-for-javascript-functions.aspx
And, if you are going to have more than one manager on the page: http://www.telerik.com/help/aspnet-ajax/radwindow-troubleshooting-wrong-window-opened.html.
That way probably you get errors stating that the window is null
Try it like this:
Code behind:
string script = "<script language='javascript' type='text/javascript'>Sys.Application.add_load(ShowWindow);</script>";
ClientScript.RegisterStartupScript(this.GetType(), "showWindow", script);
Then on your aspx:
<script type="text/javascript">
function ShowWindow()
{
var oWnd = window.radopen('https://www.google.co.in/', 'window1');
}
</script>

Update Panel + window.open + https

I'am developing with c# and asp.net.
I have some pages with update panels. In this update panels there is a button that redirects to a new window. This is done by calling the window.open with the scriptmanager in code behind. Everything works fine until I don't use https. If I use tunnelling with a router to have a secure line till the router and then use a proxy to access my webpages, the window.open called from the buttons that are in an update panel open a new register card, but there I get the error : page not found. In the url I can see that the router did not put the proxy+IP before the path. That does not happen if I remove the update panel.With Firebug I could see that with the update panel I get a POST and in the resonse the contentType is text/plain. Without the update panel there is a GET and the response contentType is text/html. So what can I do to run this without removing the update panels?
This works fine until I don't use https over my proxy:
protected void btnPrint_Click(object sender, EventArgs e)
{
url = "~/Gui/Report/ReportViewer.aspx?ReportName=CustomerReport";
Page page = (Page)HttpContext.Current.Handler;
if (page == null) {
Redirect(url);
}
url = page.ResolveUrl(url);
string script = #"window.open(""{0}"");";
script = String.Format(script, url);
ScriptManager.RegisterStartupScript(page,
typeof(Page),
"Redirect",
script,
true);
}
<asp:UpdatePanel ID="UpdatePanel" runat="server">
<ContentTemplate>
<dx:ASPxButton runat="server" ID="btnPrint"
Text="print" OnClick="btnPrint_Click">
</dx:ASPxButton>
</ContentTemplate>
</asp:UpdatePanel>
Got it....
the information that the scriptlanguage is javascript is lost if I am using the proxy (strange...?!?!).
If I build the script tags on my own with adding the attribut "language='javascript'" then everything works fine.
Can anybody tell me why this information is lost?
Here the new code:
protected void btnPrint_Click(object sender, EventArgs e)
{
url = "~/Gui/Report/ReportViewer.aspx?ReportName=CustomerReport";
Page page = (Page)HttpContext.Current.Handler;
url = page.ResolveUrl(url);
string script = "window.open('" + url + "');";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script language='javascript'>");
sb.Append(script);
sb.Append("</script>");
ScriptManager.RegisterStartupScript(page,
typeof(Page),
"Redirect",
script,
false);
}

Categories

Resources