cannot get the newest button name in C# - javascript

my asp project has a asp button which named 'Save'. However, i need to change it to 'Update' in jQuery to do other thing in one button.
The problem is the C# onclick code is still read it as Save..
Code:
//Main
<asp:Button ID="btnSubmit" runat="server" Text="Save" />
//JQuery
$("#<%=btnSubmit.ClientID %>").val("Update");
//C#
var button = sender as Button;
var buttonName = button.Text; //Save
Update1
Question is:
I need to change the button name in JQuery
$("#<%=btnChangeName.ClientID %>").click({
$("#<%=btnSubmit.ClientID %>").val("Update"); //Change Save to Update
});
Then use it in C#:
protected void btnSubmit_Click(object sender, EventArgs e)
{
var button = sender as Button;
var buttonName = button.Text;
if (buttonName == "Save")
{//something}
else
{//something}
}

if you want to change the Name to Update1 in Jquery
try like this
$("#<%=btnSubmit.ClientID%>").val('Update');
Event you neeed to use is OnClientClick
Usage example
OnClientClick="onupd();return false;"
Update
Decalre a Hidden FIeld
<asp:HiddenField runat="server" ID="hdntest" Value="0" />
assign the button change value to update and assign it to the hidden field
not access that hidden value in your code behind.
you can assign Button value to Hidden Field like this
$("#<%=btnSubmit.ClientID %>").val("Update");
$("#<%=hdntest.ClientID%>").val($("#<%=btnSubmit.ClientID%>").attr("value"));

If you change the Button.Click value, then it will move to a different method onClick;
private void Form1_Load(object sender, EventArgs e)
{
Button b = new Button();
b.Name = "btnSubmit";// creating here for intellisense - you would create on your front-end
bool recordExists = true;
Button b1 = Controls.Find("btnSubmit", true)[0] as Button;
//the above is for winforms - you'd have to change for web form
b1.Text = recordExists ? "Update" : "Save";
b1.Click += doUpdateOrSave;
}
protected void doUpdateOrSave(object sender, EventArgs e)
{
Button b = sender as Button;
if (b.Text == "Save")
{
//save
}else
{
//update
}
}

Related

How to pass a value from JavaScript to code behind?

I want get a value from js to code behind but the value is always an empty string.
I tried to pass the value from js to a label with runat="server" specified but in vain.
html:
<input type="hidden" runat="server" id="Val1"/>
js:
document.getElementById("Val1").value = MyFunction();
function MyFunction()
{
var value = "111";
}
code behind:
protected void sss(object sender, EventArgs e)
{
string aa = Val1.Value;
}
You could also use the Session to return your data.
In js:
sessionStorage.setItem('Val1', '111');
In code behind:
int Val1 = Convert.ToInt32(Session["Val1"]);
Use this
var val = document.getElementById('<%=val1.Client ID%>');
val.value= "111';
In your cs use val1.value

Calling button click on file upload inside gridview

I'm trying to upload a file onchange event of the "Fileupload" control inside gridview.
Means when ever user uploads the file, there itself I needs to save the file content in DB.
So, I had mannually called the click event of the button control on the change of fileupload control But its throwing as like exception like "Invalid postback or callback argument...."
my gridview code :
<asp:GridView runat="server" ID="grd" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="StudentID" HeaderText="Student ID" />
<asp:BoundField DataField="StudentName" HeaderText="Name" />
<asp:TemplateField HeaderText="Upload">
<ItemTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" EnableViewState="true" onChange="FileUploadCall(this)" />
<asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="Upload" Style="display: none" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My script Code :
<script type="text/javascript">
function FileUploadCall(fileUpload) {
if (fileUpload.value != '') {
var a = $('#<%=grd.ClientID %>').find('[id*="btnUpload"]');
a.click();
}
}
</script>
My Hidden Button mannual click creation in cs file :
protected void Upload(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gvr = (GridViewRow)btn.Parent.Parent;
FileUpload lbleno = (FileUpload)gvr.FindControl("FileUpload1");
lbleno.SaveAs(Server.MapPath("~/Uploads/" + Path.GetFileName(lbleno.FileName)));
//lblMessage.Visible = true;
}
Your jquery code that gets the button to upload may be the reason.
Since you said you are using a gridview, so there could be multiple rows each having its own fileupload and button controls. You need to get the button control associated with this row in grid view. To get the associated button, you should be using the jquery code like below, since the associated button immediately follows the fileupload control.
if (fileUpload.value != '') {
var a = $(fileUpload).next("[id*='Button1']");
a.click();
}
The easiest way is to assign the onchange event from code behind so you can get the correct button easily. So create a RowDataBound event for the GridView.
<asp:GridView ID="grd" runat="server" OnRowDataBound="grd_RowDataBound">
Then in the RowDataBound method, use FindControl to locate and cast the FileUpload and the Button. In the method you can assign the change event to trigger a PostBack of the corresponding button.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//use findcontrol to locate the controls in the row and cast them
Button btn = e.Row.FindControl("btnUpload") as Button;
FileUpload fu = e.Row.FindControl("FileUpload1") as FileUpload;
//assign the button postback to the change of the fileupload
fu.Attributes.Add("onchange", "__doPostBack('" + btn.UniqueID + "','')");
}
}
Your implementations is fine only change:
a.click(); => a[0].click(); //important!!
and I hope no binding is happening in the postback:
if (!IsPostBack)
{
var list = new List<Student>();
list.Add(new Student() {StudentID = 1, StudentName = "111"});
list.Add(new Student() {StudentID = 2, StudentName = "222"});
grd.DataSource = list;
grd.DataBind();
}
I've tested it works totally fine!

Disabling ListBox on Page_Load

I'm trying to disable the two list boxes on load of my web form, but the list boxes are not disabling. I tried the code below but it's still not working on my case. Please let me know where I'm going wrong.
DESIGNER CODE
<telerik:RadListBox ID="lbSelectedDepartmentContacts" runat="server" Width="220px" AutoPostBackOnTransfer="true" AutoPostBackOnReorder="true" AutoPostBackOnDelete="true" CheckBoxes="false" AllowTransfer="true" AllowTransferOnDoubleClick="true" TransferToID="lbDepartmentContacts"
Height="276px" SelectionMode="Single" AllowReorder="True">
<ButtonSettings ShowTransfer="false" ShowTransferAll="false" ReorderButtons="Common" ShowReorder="true" />
</telerik:RadListBox>
</td>
</tr>
<tr>
<td align="right">
<telerik:RadListBox ID="lbDepartmentContacts" runat="server" Width="200px" CheckBoxes="false" AutoPostBackOnTransfer="true" AllowTransfer="true" AllowTransferOnDoubleClick="true" TransferToID="lbSelectedDepartmentContacts"
Height="250px" SelectionMode="Single">
<ButtonSettings TransferButtons="Common" ShowTransfer="false" ShowTransferAll="false" />
</telerik:RadListBox>
BACKCODE
public void DisableControls()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(#"<script language='javascript'>function DisableControls(){");
sb.Append(#"var lbl = document.getElementById('lbSelectedDepartmentContacts').disabled = true;");
sb.Append(#" var Txt = document.getElementById('txtDepartmentCategoryContactsFilter').disabled = true;");
sb.Append(#" var btn = document.getElementById('RadButton1').disabled = true;");
sb.Append("}</script>");
if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock",
sb.ToString());
}
string funcCall = "<script language='javascript'>DisableControls();</script>";
if (!ClientScript.IsStartupScriptRegistered("JSScript"))
{
ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall);
}
}
Tried Also:
Page.ClientScript.RegisterStartupScript(this.GetType(), "text", "DepartmentLoad();", true);
JAVASCRIPT CODE
function DepartmentLoad(){
document.getElementById("lbSelectedDepartmentContacts").disabled = true;
document.getElementById("lbDepartmentContacts").disabled = true;
document.getElementById("txtDepartmentCategoryContactsFilter").disabled = true;
ducument.getElementById("RadButton1").disabled = true;}
C# only approach to disable your 2 listboxes...
Delete or comment out your existing DisableControls() method then add the following...
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) return;
DisableControls();
}
private void DisableControls()
{
lbSelectedDepartmentContacts.Enabled = lbDepartmentContacts.Enabled = false;
}
You should generally:
Use Sys.Application.Load to register your script. Calling the function earlier will cause problems with using the client-side API of the IScriptControls: http://msdn.microsoft.com/en-us/library/bb383829.aspx and http://docs.telerik.com/devtools/aspnet-ajax/controls/window/troubleshooting/executing-javascript-code-from-server.
use the API the Telerik control provides: http://docs.telerik.com/devtools/aspnet-ajax/controls/listbox/client-side-programming/objects/radlistbox-object.
There seems to be no set_enabled() or set_disabled() method on the client (at least at the time of writing), so this seems to be impossible with JS, so you should go with the other answer that tells you to use server code.

drop down list not post back-javascript

I have a tabpanel with a dropdownlist control on the 4th tab but when I select a item, the postback not occur even autopostback property is true. Is there any way to postback the page when item is selected?
I think this use the javascript code to postback the drop down list please suggest.
Any ideas ?
<asp:DropDownList ID="ddlrole" runat="server" Width="151px" AutoPostBack="True"
onselectedindexchanged="ddlrole_SelectedIndexChanged">
</asp:DropDownList>
code behind is:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//code goes here
}
}
protected void ddlrole_SelectedIndexChanged(object sender, EventArgs e)
{
st = int.Parse(ddlrole.SelectedValue);
}
ddlrole_SelectedIndexChanged is not fire when an item is selected from drop down list?
I use the javascript code to prevent this tab to return to first tab:
<script type="text/javascript">
$(function () {
$("#tabContainer").tabs();
var currTab = $("#<%= HFCurrTabIndex.ClientID %>").val();
$("#tabContainer").tabs({ selected: currTab });
});
</script>

How to enable asp:LinkButton on client side

I have asp:LinkButton, input Button defined as:
<asp:LinkButton ID="lnkViewPdf" runat="server" CssClass="icoMiniTest" ClientIDMode="Static" >View Office Pdf</asp:LinkButton>
<input id="Button2" type="button" value="TestEnable" onclick="TestEnable(document.getElementById('lnkViewPdf'));" />
the LinkButton is initially disabled in code-behind as:
if (!IsPostBack)
{
this.lnkViewPdf.Enabled = false;
}
and needs to be enabled when Button2 is clicked, so I am calling javascript function to enable the link as:
function TestEnable(lnkbutton) {
alert('TestEnable() called');
alert(lnkbutton.id);
lnkbutton.disabled = "";
//$("#lnkbutton").removeAttr('disabled'); //even this doesn't work
}
But I am not able to enable the linkbutton.
Am I missing something?
Thank you!
__________________________________________________
Anyone interested in solution to above problem:
In code-behind:
this.lnkViewPdf.Attributes["disabled"] = "disabled";
this.lnkViewPdf.Attributes["onclick "] = "return false";
.js:
function TestEnable(lnkbutton) {
$(lnkbutton).removeAttr('disabled');
lnkbutton.onclick = "";
}
NOTE: When setting lnkViewPdf.Enabled = false; LinkButton was being rendered as
<a id="lnkViewPdf" class="aspNetDisabled icoMiniTest">View Office Pdf</a>
see the style class aspNetDisabled, something added by ASP.Net
However setting disabled/onclick attributes from the codebehind as shown above, render Linkbutton as:
<a id="lnkViewPdf" class="icoMiniTest" disabled="disabled" onclick ="return false" href="javascript:__doPostBack('lnkViewPdf','')">View Office Pdf</a>
HTH.
Try now...
function TestEnable(lnkbutton) {
lnkbutton.disabled = "";
lnkbutton.onclick = "";
}
In the code behind, rather than disable by setting Enabled = false, set:
lnkViewPdf.Attributes["disabled"] = "disabled"
So your javascript function:
function TestEnable(lnkbutton) {
alert('TestEnable() called');
alert(lnkbutton.id);
lnkbutton.disabled = "";
}
Your markup:
<asp:LinkButton ID="lnkViewPdf" runat="server" CssClass="icoMiniTest" ClientIDMode="Static" >View Office Pdf</asp:LinkButton>
<input id="Button2" type="button" value="TestEnable" onclick="TestEnable(document.getElementById('<%= lnkViewPdf.ClientID %>')); return false;" />
And your code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
lnkViewPdf.Attributes["disabled"] = "disabled";
}
$("#<%=lnkViewPdf.ClientID %>").removeAttr("disabled");
You need to know the .Net constructed name in order to accomplish it. The easiest way is to have it set in the head of the page if you can:
<script language="javascript">
var lnkbuttonToEnableId = "<%= this.lnkViewPdf.ClientId %>";
function TestEnable() {
alert('TestEnable() called');
lnkbuttonToEnableId.disabled = false;
}
</script>
At any rate, the only way to get it to work is to pass the ClientId of lnkViewPdf to the function somehow.
try both of those:
<input id="Button2" type="button" value="TestEnable"
onclick="TestEnable(document.getElementById('<%= lnkViewPdf.ClientID %>'));" />
or
$("#<%= lnkViewPdf.ClientID %>").removeAttr('disabled');
UPDATE: Since you are disabling the LinkButton on server side .NET strips the href attribute from the <a> html element. What you should do to prevent the lost of that information is to disable the LinkButton on the client and then enable it when you need to. Also instead of disabling it all you need to do is remove the href attribute.
So first you need to retain the href and remove it so the <a> link become disabled:
$(document).ready(function () {
var $lnkViewPdf = $("#lnkViewPdf");
$lnkViewPdf.data("href", $lnkViewPdf.attr("href"));
$lnkViewPdf.removeAttr("href");
});
and the function that enables it:
function TestEnable(lnkViewPdfId) {
var $lnkViewPdf = $("#" + lnkViewPdfId);
$lnkViewPdf.attr("href", $lnkViewPdf.data("href"));
}
If you disable the LinkButton using:
if (!IsPostBack)
{
this.lnkViewPdf.Enabled = false;
}
Then the href attibute won't be displayed in the HTML. If you manually add the disabled attribute instead:
if (!IsPostBack)
{
lnkViewPdf.Attributes.Add("disabled", "disabled");
}
Then you're code will work just fine.
Oh!.. and one last thing: You need to set the PostBackUrl property for the LinkButton. You missed it in your example.

Categories

Resources