ASP.NET Webforms Multiple Buttons - c#

I'm making a ASP.NET Web Forms application. I am trying to have a simple way where I can access several controls on the form.
I am trying to access html buttons' serverClick event but it has not been working and only worked on a single button per page.
I first tried to use this code to get the click event when the HTML button was clicked. This is the code for the HTML button.
<form runat="server">
<div class="btn-container">
<a runat="server" onserverclick="infobutton_Click" class="inf-btn" exc-content="inf_button" id="infoButton">Click Here for More Information</a>
</div>
</form>
This code gets the button's click event and displays a sample message box.
Protected Sub infoButton_Click(ByVal sender As Object, ByVal e As EventArgs)
ScriptManager.RegisterClientScriptBlock(Me, Me.[GetType](), "alertMessage", "alert('" & "The Button Was Clicked" & "')", True) 'Displays a JavaScript Alert
End Sub
This code works fine for one button per page, however, I want to use multiple buttons on one page. If I remove the <form> tag, the button click event does not register. If I add a <form> tag for each and every button, it reports an error that there cannot be multiple <form> tags. If I enclose the whole page with a <form> tag, the error reports that the configuration is "corrupted".
This would be straightforward if I had a ASP.NET button control (<asp:button>), but I cannot convert all elements on the page.
I'm not sure what is wrong as all information online says it is correct. Is there any way I can fix this?

<body>
<form id="form1" runat="server">
<div class="btn-container">
<a runat="server" onserverclick="infobutton1_Click" id="infoButton1">
Click Here for More Information</a>
<a runat="server" onserverclick="infobutton2_Click" id="infoButton2">
Click Here for More Information</a>
<a runat="server" onserverclick="infobutton3_Click" id="infoButton3">
Click Here for More Information</a>
</div>
</form>
</body>
Code Behind (C#)
protected void infobutton1_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, Page.GetType(),
"alertMessage", "alert('" + "Button 1 Was Clicked" + "')", true);
}
protected void infobutton2_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, Page.GetType(),
"alertMessage", "alert('" + "Button 2 Was Clicked" + "')", true);
}
protected void infobutton3_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, Page.GetType(),
"alertMessage", "alert('" + "Button 3 Was Clicked" + "')", true);
}

Related

asp button add through span not firing Click event

This is my front End Code in asp.net form
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<span id="Message" runat="server"></span>
<span id="myid" runat="server">
</span>
</asp:Content>
here is my code behind
protected void Page_Load(object sender, EventArgs e)
{
myid.InnerHtml = myid.InnerHtml + "<asp:Button ID=" + dbLayer.AddDoubleQuotes("Button_Update") + " name=" + dbLayer.AddDoubleQuotes("Button_Update") + " runat=" + dbLayer.AddDoubleQuotes("server") + " class=" + dbLayer.AddDoubleQuotes("btn btn-success") + " OnClick=" + dbLayer.AddDoubleQuotes("Button_Update_Click") + " Text=" + dbLayer.AddDoubleQuotes("UpdateButton") + " />";
}
protected void Button_Update_Click(Object sender, EventArgs e)
{
Message.InnerHtml = "This Event Fired Sucessfully ...";
}
i am using web Method for Double Quotes
[WebMethod]
public string AddDoubleQuotes(string value)
{
return "\"" + value + "\"";
}
Not Able to get button click event
your reply helps me lot, i am stuck due to this
First of all, you cannot just simply render Server Control as string literal in ASP.Net Web Form.
Dynamically added server controls are a little bit tricky since they are not in control tree. You need to reload them back with same ID inside either Page_Init or Page_Load event.
<asp:PlaceHolder ID="PlaceHolder1" runat="server" />
<asp:Label runat="server" ID="MessageLabel" />
protected void Page_Init(object sender, EventArgs e)
{
var button = new Button {ID = "Button1"};
button.Click += Button_Click;
PlaceHolder1.Controls.Add(button);
}
private void Button_Click(object sender, EventArgs e)
{
MessageLabel.Text = "Button is clicked!";
}
FYI: Use ASP.Net Server control as much as possible instead of regular html control with runat="server", unless you absolutely certain that you do not need ViewState and some extra features offered by those server controls.
If EnableViewState is false, you can repopulate placeholder controls with different controls dynamically on a postback. The ids do not matter then.

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;
}

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.

Hide tab header on ajax:TabContainer

Based upon my condition I only want to remove tabheader from ajax:TabContainer on button click.
My function is:
<script type="text/javascript">
//<![CDATA[
function hideheadertab() {
$('.ajax__tab_header').hide();
}
//]]>
</script>
And in button click I call function like this.
protected void btnAdd_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "tmp", "<script type='text/javascript'>hideheadertab();</script>", true);
}
but no luck.Any trick to do this.Thanks for help.
Note: I want to remove only tab header not whole tab.
tab header html part.
<div id="ctl16_TabContainerManagePortal_header" class="ajax__tab_header">
<span id="ctl16_TabContainerManagePortal_TabPanelPortalAddEdit_tab" class="ajax__tab_active"><span class="ajax__tab_outer"><span class="ajax__tab_inner"><span id="__tab_ctl16_TabContainerManagePortal_TabPanelPortalAddEdit" class="ajax__tab_tab">
<span id="ctl16_TabContainerManagePortal_TabPanelPortalAddEdit_lblAEP">Some Text</span>
</span></span></span></span>
</div>

ASP - file upload in single step

Browse and Upload with using asp:FileUploadcontrol is working perfectly fine.
But It is two step process. First we have to browse and then select the file.
I want it working in single step So for making it single step I tried the following code:
protected void Button1_Click(object sender, EventArgs e)
{
//to launch the hidden fileupload dialog
ClientScript.RegisterStartupScript (GetType(),
"hwa", "document.getElementById('fileupload').click();", true);
//Getting the file name
if (this.fileupload.HasFile)
{
string filename = this.fileupload.FileName;
ClientScript.RegisterStartupScript(GetType(), "hwa", "alert('Selected File: '" + filename + ");", true);
}
else
{
ClientScript.RegisterStartupScript(GetType(), "hwa", "alert('No FILE has been selected');", true);
}
}
In this code, there is one fileUpload control that is being invoked on Button1_Click. Ideally it should execute the first line then A file Upload control should be shown and after selecting a file or canceling the dialog, flow should go to next line. But dialog is showing up after full function execution finishes.
Because of this asynchronous or not expected execution flow if (this.fileupload.HasFile) is returning false(because user has not been asked to select any file yet) and I am not getting the selected file name.
Can we modify this code to achieve file upload in single step? Or if any other way is possible to do this?
Note- I have asked not to use window forms and Threads. So solution by using these two is not acceptable.
You are missing the fact there is a client side/server side disconnect in the web environment.
Your line: ClientScript.RegisterStartupScript (GetType(),"hwa","document.getElementById('fileupload').click();", true); is client side code and will not be executed until the serverside script is comleted and the resulting HTML/javascript/CSS returned to the browser as it is client side javascript. YOu want to be leveraging the onchange event of the file upload control.
The question should help you out: ASP.NET FileUpload: how to automatically post back once a file is selected?
this is not exactly what you are looking for but it does what you want. difference is that instead of clicking a separate button you have to click the Browse button. and when you press the Open button, the page will postback. I have used JQuery for this. here's my code
ASPX
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.9.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fileupload1" runat="server" />
<asp:Button ID="btn" runat="server" OnClick="btn_Click" Text="upload" style="display:none" />
</div>
<script type="text/javascript">
var isfirst = true;
$(function () {
$('#<%= fileupload1.ClientID %>').on('change', function (e) {
console.log('change triggered');
$('#<%= btn.ClientID%>').trigger('click'); // trigger the btn button click which i have hidden using style='display:none'
});
});
</script>
</form>
</body>
Code behind
protected void btn_Click(object sender, EventArgs e)
{
//TODO
}
For the ones who land here late,
<div>
<asp:FileUpload ID="fu" runat="server" CssClass="bbbb" onchange="clickSeverControl()"/>
<asp:LinkButton Text="Upload" ID="lnkUpload" runat="server" OnClientClick="showUpload();return false;" OnClick="lnkUpload_Click"/>
</div>
hide the file control with css
<style>
.hiddenStyle {
visibility:hidden;
}
</style>
on client click event of link button trigger the click of file upload control
function showUpload() {
document.getElementById("fu").click();
}
on change event trigger the server side click
function clickSeverControl() {
__doPostBack('<%= lnkUpload.ClientID %>', 'OnClick');
}
on server click save the uploaded file
protected void lnkUpload_Click(object sender, EventArgs e)
{
fu.PostedFile.SaveAs(Server.MapPath("~/Upload") + "/" + fu.PostedFile.FileName);
}
Thanks for the other answer I have just combine two example and got the solution for my problem in my project
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.9.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fileupload1" runat="server" />
<asp:Button ID="btnUploadBulk" runat="server" OnClick="btn_Click" Text="upload" style="display:none" />
</div>
<script type="text/javascript">
var isfirst = true;
$(function () {
$('#<%= btnUploadBulk.ClientID%>').on('click', function (e) {
showUpload();
})
});
function showUpload() {
var control = document.getElementById("<%= FileUploadControl.ClientID %>");
control.click();
}
</script>
</form>
Code Behind
protected void btn_Click(object sender, EventArgs e)
{
//TODO
}
This worked for me

Categories