LinkButton OnClick() doesnt hit the srcipt function - c#

In my aspx page, I has a Linkbutton linkbtTitle inside a Repeater Control:
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
<script runat="server">
protected void Buttonlink_Click(object sender, System.EventArgs e)
{
LinkButton linkbtTitle = (LinkButton)sender;
linkbtTitle.ForeColor = System.Drawing.Color.HotPink;//change color when selected
linkbtTitle.Font.Underline = true;
linkbtTitle.Font.Italic = true;
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:LinkButton ID="linkbtTitle" runat="server" Text='<%#Eval("TITLE")%>' CommandArgument='<%#Eval("ID")%>' OnCommand="linkbtTitle_Click" OnClick="Buttonlink_Click" ></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
I use method OnCommand="linkbtTitle_Click" to auto download attachment when client click on Linkbutton and OnClick="Buttonlink_Click" to change color of selected Linkbutton.
When I built this page, the attachment is downloaded automatically but the Selected LinkButton doesnt change its color.
Try to debug, function Buttonlink_Click() is not called, it has an message: Expression Statement is not assignment or call when hovering mouse on statement: ... OnClick="Buttonlink_Click" ...
I wonder if there is some problem in linkbtTitle_Click Please take a look at my code behind:
public void linkbtTitle_Click(object sender, CommandEventArgs e)
{
//auto download the attachment when selected
int mamd = Convert.ToInt32(e.CommandArgument.ToString());
string sql = "select * from MAU_DON where MA_MAU_DON="+mamd;
DataTable maudon = l.EXECUTEQUERYSQL(sql);
string attachment = dirPath["MAU_DON"].DIRECTORY + #"/" + maudon.Rows[0]["PATH"].ToString();
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition",
"attachment; filename=" + Path.GetFileName(attachment));
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.WriteFile(attachment);
HttpContext.Current.Response.End();
}

It will not hit the server side function. The eventing mechanism is slightly altered when a control like linkbutton or even a normal button itself is used in the item template. Instead of the onclick event firing, an event on the repeater will fire...its called ItemCommand. This happens via a mechanism called event bubbling.
To know which button caused it, you need to use the CommandName and CommandArgument.
<asp:LinkButton ID="lnkbtn" runat="server" CommandName="foo" CommandArgument="<%# Eval ("Id") %>" Text="FooBtn" />
In the code behind, the repeater's item command event, we write something like
if (e.CommandName == "foo")
{
// so we know what button triggered this
// access the value of e.CommandArgument to get associated row data.
}

Related

Calling asp net button click event with JS will not call server side event

Sorry to post perhaps a silly problem here, but I'm at my wits end with it. I have a hidden field with a button inside an update panel like so:
<asp:UpdateProgress runat="server" ID="updprCompLines" AssociatedUpdatePanelID="updpanCompLines">
<ProgressTemplate>
<img src="../Images/ajax-loader.gif" alt="Please wait..." /> </ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel runat="server" ID="updpanCompLines" UpdateMode="Conditional">
<%--<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnFillMembers" />
</Triggers>--%>
<ContentTemplate>
<div>
<asp:HiddenField ID="hdnField" runat="server" />
<asp:Button ID="btnFillMembers" runat="server" style="display:none;"
Text="DummyButton" onclick="btnFillMembers_Click" />
</div>
The update panel also contains a gridview and inside my gridview I have a link button:
<ItemTemplate>
<asp:LinkButton ID="lkbtBenefName" runat="server" Text='<%#Eval("COMPETENCE_CODE") %>'
OnClientClick='<%#Eval("COMPETENCE_LINE_ID", "return SelectedCompetence({0})") %>'/>
</ItemTemplate>
The call is to a JS function that is supposed to call the above button:
<ajaxToolkit:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="ScriptManager1" EnablePageMethods="true"/>
<script type="text/javascript">
function SelectedCompetence(CompetenceLineId) {
document.getElementById('<%= hdnField.ClientID %>').value = CompetenceLineId;
var clickButton = document.getElementById('<%= btnFillMembers.ClientID %>');
clickButton.click();
}
</script>
Button click event method:
protected void btnFillMembers_Click(object sender, EventArgs e)
{
lblGvMemError.Text = "";
lblGvMemError.ForeColor = Color.Red;
if (hdnField.Value != null || hdnField.Value.ToString() != "")
{
try
{
int CompLineId = Convert.ToInt32(hdnField.Value);
GetSelectedCompLineMembers(CompLineId);
}
catch (Exception ex)
{
lblGvMemError.Text = "Error: " + ex.Message;
}
}
updpanCompLinesMembers.Update();
}
The problem is that while debugging, it never runs the click event and it doesn't give any error messages either. I don't understand, I have a similar form where this works; I don't get why it doesn't here... Any help please?
Have you confirmed that SelectedCompetence is being called via an alert or similar? Additionally, have you made sure that the clickButton variable is being assigned to successfully?
I know this isn't an answer, but don't yet have the reputation to comment, and sometimes it's the easy stuff so maybe this will help! :)

radiobutton inside repeater always returns false

I have a repeater with radiobuttons in it.
<script type="text/javascript">
$(document).ready(function ()
{
$("#test input:radio").attr("name", "yourGroupName");
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="test">
<asp:Repeater runat="server" ID="rep" onitemdatabound="rep_ItemDataBound"
onitemcommand="rep_ItemCommand">
<ItemTemplate>
<asp:RadioButton ID="n" runat="server" Text='<%# Eval("name") %>' AccessKey='<%# Eval("id")%>' />
</ItemTemplate>
</asp:Repeater>
</div>
I am using the javascript at the top to fix the radiobutton bug in .net.
i bind a list to the repeater at page load, with a if (!Page.IsPostback) around it.
edit:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
rep.DataSource = z.Table.ToList();
rep.DataBind();
}
}
then i have a button, that when clicked should do something with the radio button that's been selected, this is the problem now:
foreach (RepeaterItem i in rep.Items)
{
RadioButton erb = i.FindControl("n") as RadioButton;
if (erb.Checked)
{
//do stuff
}
}
no matter which radiobutton i select, when i click the button and i debug the entire loop, every checkbox == false. i'm doing more stuff with the code but i've simplified it, because this is the biggest problem.
i have seen countless of topics about this issue and i have looked through them all but i still can't seem to get this to work.
Please try adding OnCheckedChanged="RadioButton1_OnCheckedChanged" AutoPostBack="true" on you radio button this will trigger post back on click of the button and you will be able to find the Checked one
I think this is all down to the sequence of events in ASP.NET .
Try putting your DataBind code in the Page_Init procedure, that way the state of the radiobuttons will be set by the time it reaches the Page_Load procedure.

Unable to retrieve DDL SelectedValue bound in ASPX after Page Load

I have the following markup / code block in the ASPX file.
The binding of the ddl is triggered after Page_Load event which is in the code behind file.
This results me not able to get the selected value of the dropdownlist if I were to use such flow.
However for some purpose I require it to work this way.
Any idea how I could get the dropdownlist selected value when a post back is being triggered (click of the button)?
Page URL: page.aspx?para1=0&para2=value
ASPX PAGE
<%
if (Convert.ToInt32(Request.QueryString["para1"]) == 0)
{
ddl.DataValueField = "value";
ddl.DataTextField = "text";
ddl.DataSource = ds; //ds is valid, exact code not shown
ddl.DataBind();
} else {
//write in this area
Response.Write("Not 0");
}
%>
<form runat="server" id="user_form" class="form-horizontal">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:UpdatePanel ID="updPanel" runat="server">
<ContentTemplate>
<asp:DropDownList runat="server" ID="ddl">
</asp:DropDownList>
<%-- this button will call btnSave_Click to get the ddl's value--%>
<asp:Button runat="server" ID="btn" Text="Button" OnClick="btn_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
CODE BEHIND
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//do my stuff
}
}
protected void btn_Click(object sender, EventArgs e)
{
int intValue = Convert.ToInt32(ddl.SelectedValue);
//do my stuff
}
The ASPX Page code block will run after Page_Load / page's lifecycle, then will determine what to do base on the url parameters.
Thanks in advance!
You could always throw in a hidden object and use jquery to copy the value to the hidden value based on a certain action without a postback and would do it client side like it sounds like you want it to do

C# Dynamically filled DropDownList resets on button OnClick

I am having a bit of a DUH moment and need some help. I have a DropDownList control that gets filled with values on page load and a submit button that does further manipulations. However, when the button is clicked DropDownList returns a value of "-1" and not of the selected option. What is wrong here?
Web page:
<%# Page Language="C#" MasterPageFile="/new/MasterPageA2.master" EnableEventValidation="false" AutoEventWireup="true" CodeFile="Checkout.aspx.cs" Inherits="Common_Checkout" EnableViewState="true" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:UpdatePanel ID="UpdatePanel" runat="server">
<ContentTemplate>
<asp:Label runat="server" ID="test11"></asp:Label>
<asp:DropDownList ID="ddlbillingcountry" required="true" EnableViewState="true" runat="server"></asp:DropDownList>
<asp:Button ID="ImageButton1" AlternateText="Proceed" OnClick="ImageButton1_Click" CausesValidation="false" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>
<p>Loading...</p>
</ProgressTemplate>
</asp:UpdateProgress>
</asp:Content>
Code behind:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
PopulateCountry(ddlbillingcountry);
}
}
private void PopulateCountry(DropDownList Controlname) {
DatasetTableAdapters.CountryTableAdapter _CountryTableAdapter = new DatasetTableAdapters.CountryTableAdapter();
Controlname.ClearSelection();
Controlname.Items.Clear();
DataTable _DataTable = _CountryTableAdapter._Eco_Country_Select();
Controlname.DataSource = _DataTable;
Controlname.DataTextField = "CountryName";
Controlname.DataValueField = "Country";
Controlname.DataBind();
Controlname.Items.Insert(0, new ListItem("- Select Country -", ""));
}
protected void ImageButton1_Click(object sender, EventArgs e) {
test11.Text += "<p>clicked " + ddlbillingcountry.SelectedIndex + " - " + ddlbillingcountry.SelectedValue.ToString();
}
You could set the datasource property to the name of a function which returns a dataset.
Try datasource='<%# PopulateCountry("ddlbillingcountry") %>' but you will need to change or overload the function to change the argument to a string, remembering to set the datavaluefield and datatextfield.Or you may want to create a separate function and call that with no arguments.

updating variable from within update panel

im trying to update a variable from within an update panel:
<script type="text/javascript">
var v = 1;
</script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="btnDone" runat="server" Text="Done" onclick="btnDone_Click" />
<asp:Literal ID="litnew" runat="server"></asp:Literal>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
function updateint() {
alert(v);
}
</script>
<input type="button" onclick="updateint()" />
code behind
protected void btnDone_Click(object sender, EventArgs e)
{
string kiss = LipImageCreator.createImage(); //this returns a file path
litnewlipsurl.Text = "<script> v = '" + kiss + "'; </script>");
}
if i click the button run the updateint() function before i hit the btnDone button i get the alert saying '1' as expected. after i click the btnDone button the javascript is written to the literal as expected but when i click the updateint() button again i still get '1' and not the filepath i was expecting....
You must use ClientScript.RegisterStartupScript() to get the ajax handler to run your script when the postback completes.

Categories