Dropdownlist losing values on button submit - c#

I have an aspx page.
THE DROPDOWN'S SELECTED VALUE IS LOST.
When i click search, i can perform a server side event and return to the page with everything working fine. When i press update, sadly, my combo boxes lose their values. I have enbabledViewState to true for master page, and current page and even on all of the controls. Any ideas how i could begin to approach this? The values are gone by the time we reach page_load event. There are no other life cycle events.
Page_Load()
{
if(!PostBack)
{
//Populate a dropdown.
This is where the dropdown is safely populated.
}
}
btnClickSearch()
{
}
btnClickUpdate()
{
}
The two buttons on the page.
NOT WORKING
<asp:Button id="btnUpdate" class="fg-button ui-state-default ui-corner-all" runat="server" Text="Update" onclick="btnClick_Update" onclientclick="return updateNotes();" style="width:auto;"/>
WORKING
<asp:Button id="A2" runat="server" onclick="btnClick_Submit" OnClientClick="return searchNotes();" class="fg-button ui-state-default ui-corner-all" style="float: left; margin-left: 20px; width:auto;" Text="Search"></asp:Button>
The onclient click event for both buttons calls blockUI and returns true. Any idea why these would be different in behaviour?
Also, none of the dropdown items have duplicate values.

Maybe you can try to set a session for selected one after pressing update button:
btnClickUpdate()
{
Session["DDLValue"] = dropdownlist.SelectedValue;
}
On page load, get the session and set it to drop down list if it is not NULL:
if(Session["DDLValue"] != null)
{
dropdownlist.SelectedValue = Session["DDLValue"].ToString();
}
Following links would help: Set selected value for drop down list

I have two controls.
Button1 and button2. Button 1 works fine. Button 2 does call it's server side event, but when this occurs we get a CKEditor dissasembly.
I have a jquery UI dialog containing the CKEditor and an asp button. When this button it clicked all of the values are lost on the server side and the disassembly is shown.
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="ckeditor/custom/dialog-patch.js"></script>
<span style="width: 500px; height: 100%">
<CKEditor:CkEditorControl id="CKEditor1" runat="server" AutoPostBack="false">
</CKEditor:CkEditorControl>
</span>
Definition
$(function() {
// to load editor
CKEDITOR.on('dialogDefinition', function(ev) {
// Take the dialog name and its definition from the event
// data.
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
// Check if the definition is from the dialog we're
// interested on (the "Link" dialog).
if (dialogName == 'link') {
// remove contents
dialogDefinition.removeContents('target');
dialogDefinition.removeContents('upload');
dialogDefinition.removeContents('advanced');
// Get a reference to the "Link Info" tab.
var infoTab = dialogDefinition.getContents('info');
// Remove the "Link Type" combo and the "Browser
// Server" button from the "info" tab.
infoTab.remove('linkType');
infoTab.remove('browse');
}
else if (dialogName == 'table') {
// Get a reference to the default tab.
var infoTab = dialogDefinition.getContents('info');
infoTab.remove('selHeaders');
infoTab.remove('txtHeight');
infoTab.remove('txtCellSpace');
infoTab.remove('txtCellPad');
infoTab.remove('txtCaption');
infoTab.remove('txtSummary');
infoTab.remove('cmbAlign');
}
});
});
Function to open the dialog containing the CKEditor.
function EditDialog(element,supplier,codeId,name, category,categoryCode, noteId,templateText) {
var numberOfNotes = $(element).parent().children('.text').length;
var noteBody = "";
if (numberOfNotes == 1) {
noteBody = $(element).parent().children('.text').html();
}
if (noteBody == "") {
noteBody = templateText;
}
$('#<%=esupplier.ClientID %>').val(supplier);
$('#<%=ename.ClientID %>').val(name);
$('#<%=enotecategory.ClientID %>').val(category);
$('#<%=hfCategoryCode.ClientID %>').val(categoryCode);
$('#<%=hfNoteID.ClientID %>').val(noteId);
$('#<%=hfIdCode.ClientID %>').val(codeId);
var dialogeditcontainer = $('#editdialog').dialog('open');
dialogeditcontainer.parent().appendTo(jQuery('form:first'));
CKEDITOR.instances[$('#editorName').val()].setData(noteBody);
return false;
}
Definition
$(function() {
// to load editor
CKEDITOR.on('dialogDefinition', function(ev) {
// Take the dialog name and its definition from the event
// data.
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
// Check if the definition is from the dialog we're
// interested on (the "Link" dialog).
if (dialogName == 'link') {
// remove contents
dialogDefinition.removeContents('target');
dialogDefinition.removeContents('upload');
dialogDefinition.removeContents('advanced');
// Get a reference to the "Link Info" tab.
var infoTab = dialogDefinition.getContents('info');
// Remove the "Link Type" combo and the "Browser
// Server" button from the "info" tab.
infoTab.remove('linkType');
infoTab.remove('browse');
}
else if (dialogName == 'table') {
// Get a reference to the default tab.
var infoTab = dialogDefinition.getContents('info');
infoTab.remove('selHeaders');
infoTab.remove('txtHeight');
infoTab.remove('txtCellSpace');
infoTab.remove('txtCellPad');
infoTab.remove('txtCaption');
infoTab.remove('txtSummary');
infoTab.remove('cmbAlign');
}
});
});
Finally the two aspx buttons. The first one works, the second one does not. The second button is located in a dialog with the ckeditor.
THIS ONE WORKS.
<asp:Button id="A2" runat="server" onclick="btnClick_Submit" OnClientClick="return searchNotes();" class="fg-button ui-state-default ui-corner-all" style="float: left; margin-left: 20px; width:auto;" Text="Search"></asp:Button>
THIS ONE DOES NOT
<asp:Button id="btnUpdate" runat="server" onclick="btnClick_Update" onclientclick="return updateNotes();" style="width:auto;" Text="Update" class="fg-button ui-state-default ui-corner-all" />
Both of the onclientclick events call BlockUI return true.

Try populating if it is a postback as well..
if(!Page.IsPostBack || Page.IsPostBack)
{
//Populate a dropdown.
This is where the dropdown is safely populated.
}
Reference... Page.IsPostBack Property

Related

ASP disable button during postback

I have a button which i am trying to add a css class to appear disabled once the user has clicked it.
protected void Button_Continue_OnClick(object sender, EventArgs e)
{
Panel_Error.Visible = false;
Literal_Error.Text = "";
if (RadioButton_Yes.Checked)
{
...//if radio checked get text and process etc.
}
}
My button onlick is above which simply processes a textbox filled on the page.
My button looks like this:
<asp:Button runat="server" ID="Button_Continue" CssClass="button dis small" Text="Continue" OnClick="Button_Continue_OnClick" ClientIDMode="Static" OnClientClick="return preventMult();" />
And my javscript is as follows:
<script type="text/javascript">
var isSubmitted = false;
function preventMult() {
if (isSubmitted == false) {
$('#Button_Continue').removeClass('ready');
$('#Button_Continue').addClass('disabled');
isSubmitted = true;
return true;
}
else {
return false;
}
}
</script>
The problem I am having is that the css class added works fine on the first postback, but after which my button onclick doesnt work and the button cant be clicked again if the user needs to resubmit the data if it is wrong
Another problem I am having is that with a breakpoint in my method i notice that the method is fired twice on the click.
Looks like you need something like this:
private void Page_Load()
{
if (!IsPostBack)
{
//doNothing
}
else
{
//button.disabled = true
}
}
try this
<asp:Button runat="server" ID="Button_Continue" AutoPostBack="true" CssClass="button dis small" Text="Continue" OnClick="Button_Continue_OnClick" ClientIDMode="Static" OnClientClick="return preventMult();" />

Change Image Using Selection in Radio Button List

I have a project that has me a bit stomped on how to proceed in the manner I would like. On one ASP.net page, I have a form that uses a radio list for the selection options. Also, I have images to the right of the categories, which I would like to change when a particular radio value selection is made.
I have researched how to do this with a regular radio button control, but I cannot seem to get over the hump, as I'm using the ASP RadioList control, and I need guidance on why I cannot get the images to change with the following code:
<script type='text/javascript'>
$(document).ready(function () {
$("input:radio[name=option]").click(function () {
var value = $(this).val();
var image_name;
if (value == 'AMD') {
image_name = "AMD_CPU_1.jpg";
} else {
if (value == 'Intel') {
image_name = "Intel_CPU_2.jpg";
} else {
image_name = "Icon_CPU.jpg";
}
}
});
});
</script>
I'm using J-Query here, and my page doesn't blow up on load - yet when I select a value, the image doesn't change. As for the [name=option]
part of the code, I don't have name="option" in the HTML code source... I have the following:
<tr>
<td><input id="MainContent_CPUBuilderForm1_radCPUType_0" type="radio" name="ctl00$MainContent$CPUBuilderForm1$radCPUType" value="AMD" /><label for="MainContent_CPUBuilderForm1_radCPUType_0">AMD</label></td>
</tr>
Where name="ctl00$MainContent$CPUBuilderForm1$radCPUType" instead.
I've tried to insert this as a replacement for "option", but still no dice. Can someone help to evaluate what I'm doing wrong here? A million thanks! Cheers.
The problem that you're having is that you're not assigning the value of the image URI to the <img> tag. So you'll need to add something to the bottom of your function to make that assignment. Since you don't have that HTML in your question, I'll write my answer with the assumption that you have a tag in your code as such: <img id="changingImage" src="" alt="" />.
So just add this to your Javascript before your function closes out:
$('#changingImage').attr('src', '../Images/' + image_name);
That should get it to change the file for you, thought you may need to change the folder it's in per your configuration.
use this
HTML
<div>
<asp:RadioButtonList ID="RadioButtonTipoUser" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Selected="true" Value="1">Dome</asp:ListItem>
<asp:ListItem Value="amd">Emp</asp:ListItem>
<asp:ListItem Value="intel">intel</asp:ListItem>
</asp:RadioButtonList>
<asp:Image ID="img" runat="server" ImageUrl="~/Desert.jpg" />
</div>
JQUERY
$(document).ready(function () {
$('#RadioButtonTipoUser_1').on('change', function () {
if ($(this).is(':checked')) {
$('#img').attr('src', 'Chrysanthemum.jpg');
}
});
$('#RadioButtonTipoUser_2').on('change', function () {
if ($(this).is(':checked')) {
$('#img').attr('src', 'Desert.jpg');
}
});
});
</script>
Welcome to the wonderful world of ASP.net Web Forms Name/ID Mangling.
Update
Having dertermined that you are using an asp.net image tag. Note that you don't have to use an asp.net control for an image you could use a plain old HTML contol with an ID instead; this ID wouldn't get mangled. However I'll stick to the asp.net image control for now.
This requires your script to be on the page and not in a js file.
.aspx
<asp:RadioBUttonList ID="yourID" runat="server" />
<asp:Image ID="Image6" runat="server" ImageUrl="~/Images/Icon_CPU.jpg" />
javascript
$(document).ready(function () {
$("#<%= yourID.ClientID %> input").click(function () {
var value = $(this).val();
var image_name;
var image_path = "/Images/";
//If the images directory isn't at the website root you could use asp.nets
//resolveURL method instead
if (value == 'AMD') {
image_name = "AMD_CPU_1.jpg";
} else {
if (value == 'Intel') {
image_name = "Intel_CPU_2.jpg";
} else {
image_name = "Icon_CPU.jpg";
}
}
//console.log(image_name);
$("#<%= Image6.ClientID %>").attr('src', image_path + image_name);
});
});
The <% %> is a server code block and should be used sparingly in aspx pages. <%= %> is short hand for `<% Response.Write() %>. If you view the source code of the page you will see the ASP.net client ID of the Radio Button List & image controls in the jQuery selectors.
You should also use a tool like FireBug for Firefox or Chrome developer tools to check the paths for the image once you click the check boxes if you are getting unexpected results. Also note the line //console.log(image_name);. Removing comments form this line will dump the value of image_name to the console, which is useful for debugging. See more info here: http://blogs.msdn.com/b/cdndevs/archive/2011/05/26/console-log-say-goodbye-to-javascript-alerts-for-debugging.aspx
Previous Code below - Doesn't address updating the image
A hacky solution is to surround you radio button list with a div or better still a fieldset and give it an id:
<div id="listContainer">
<asp:RadioButtonList ID="yourID" runat="server" />
<div>
Now update your javascript to
$(document).ready(function () {
$("#listContainer input").click(function () {
var value = $(this).val();
var image_name;
if (value == 'AMD') {
image_name = "AMD_CPU_1.jpg";
} else {
if (value == 'Intel') {
image_name = "Intel_CPU_2.jpg";
} else {
image_name = "Icon_CPU.jpg";
}
}
});
});

ASP button ID not being find "findbyelementID" in JavaScript

Trying to find Id of a ASP.Net control in JavaScript but it says ID not found, I looked at different other related question but they are all in a ASP form or alike, however here I am using DIV tags, and its giving me error on page,
Code :
<asp:Content ID="Content4" ContentPlaceHolderID="cphSubmit" runat="server">
<div id="divConfMessage" style="BORDER-RIGHT:black thin solid; BORDER-TOP:black thin solid; DISPLAY:none; Z-INDEX:200; BORDER-LEFT:black thin solid; BORDER-BOTTOM:black thin solid; background-color:white;">
<br />
<br />
<div style="BACKGROUND-COLOR: white;TEXT-ALIGN: center" id="confirmText"></div>
<div style="Z-INDEX: 105;HEIGHT: 22%;BACKGROUND-COLOR: white;TEXT-ALIGN: center"></div>
<div style="Z-INDEX: 105;BACKGROUND-COLOR: white;TEXT-ALIGN: center">
<asp:Button ID="btnConfOK" Width="200px" Height="25px" CssClass="gradientbutton" OnClick="btDelete_Click" Runat="server" Text="Yes"></asp:Button>
<asp:Button ID="btnConfCancel" Width="200px" Height="25px" CssClass="gradientbutton" Runat="server" Text="No"></asp:Button>
</div>
</div>
<script type="text/javascript" src="/_layouts/1033/jquery.js"></script>
<script type="text/javascript" language="JavaScript" src="CustomDialog.js"></script>
<script type="text/javascript" language="JavaScript">
function ShowMessage()
{
DisplayConfirmMessage('Do you really want to delete this decision?',480,120);
document.getElementById('<%=btnConfOK.ClientID%>').focus();
//SetDefaultButton('btnConfOK');
return false;
}
</script>
<asp:Button ID="btDelete" runat="server" CausesValidation="False" CssClass="gradientbutton"
UseSubmitBehavior="False"
OnClientClick="this.disabled=true;this.value='Please Wait...';ShowMessage();"
Text="Delete" Width="200px" />
EDIT:
I made the changes and the Dialog box comes up and disappears then :|, I think I need to add the control to DOM but got no clue how i gonna do that in this context :|
here's the tutorial link i followed
Dialog box tutorial
js script
var divWidth = '';
var divHeight = '';
var txtFirstButton = 'OK';
var txtSecondButton = 'Cancel'
function DisplayConfirmMessage(msg,width,height)
{
// Set default dialogbox width if null
if(width == null)
divWidth = 180
else
divWidth = width;
// Set default dialogBox height if null
if(height == null)
divHeight = 90
else
divHeight = height;
// Ge the dialogbox object
var divLayer = document.getElementById('divConfMessage');
// Set dialogbox height and width
SetHeightWidth(divLayer)
// Set dialogbox top and left
SetTopLeft(divLayer);
// Show the div layer
divLayer.style.display = 'block';
// Change the location and reset the width and height if window is resized
window.onresize = function() { if(divLayer.style.display == 'block'){ SetTopLeft(divLayer); SetHeightWidth(divLayer)}}
// Set the dialogbox display message
document.getElementById('confirmText').innerHTML = msg;
}
function SetTopLeft(divLayer)
{
// Get the dialogbox height
var divHeightPer = divLayer.style.height.split('px')[0];
// Set the top variable
var top = (parseInt(document.body.offsetHeight)/ 2) - (divHeightPer/2)
// Get the dialog box width
var divWidthPix = divLayer.style.width.split('px')[0];
// Get the left variable
var left = (parseInt(document.body.offsetWidth)/2) - (parseInt(divWidthPix)/2);
// set the dialogbox position to abosulute
divLayer.style.position = 'absolute';
// Set the div top to the height
divLayer.style.top = top
// Set the div Left to the height
divLayer.style.left = left;
}
function SetHeightWidth(divLayer)
{
// Set the dialogbox width
divLayer.style.width = divWidth + 'px';
// Set the dialogbox Height
divLayer.style.height = divHeight + 'px'
}
function SetDefaultButton(defaultButton)
{
// Set the focus on the Cancel button
document.getElementById(defaultButton).focus();
}
If I remove "UseSubmitBehavior="False", It works fine, except when I click on Yes, it doesn't closes the Dialog box
getElementById takes a string, so you need to quote the id, like this:
document.getElementById('<%=btnConfOK.ClientID%>').focus();
You have to put the output in quotes:
document.getElementById(<%=btnConfOK.ClientID%>)
should be
document.getElementById("<%=btnConfOK.ClientID%>")
You missing the syntax document.getElementById("<%=btnConfOK.ClientID%>").focus();
Read more about document.getElementById
Edit
function ShowMessage()
{
DisplayConfirmMessage('Do you really want to delete this decision?',480,120);
document.getElementById("<%=btnConfOK.ClientID%>").focus();
//SetDefaultButton('btnConfOK');
return false;
}
If your delete button doing the post-back, use event.preventDefault on delete button click.

ASP.NET C# - Retrieving HTML Button from Repeater

I have a repeater containing, amongst others, two buttons. One of the buttons is an ASP.NET button whilst the other is of the type "input type="button"".
Now, in my code-behind, I want to retrieve both buttons from the repeater to either hide them or show them. I have successfully hidden the ASP.NET button however I do not know how to retrieve the other button.
Here is some code in ASP.NET:
<input type="button" name="ButtonEditUpdate" runat="server" value="Edit Update" class="ButtonEditUpdate" />
<asp:Button ID="ButtonDeleteUpdate" CssClass="ButtonDeleteUpdate" CommandName="Delete" runat="server" Text="Delete Update" />
Here is the code-behind:
protected void RepeaterUpdates_ItemBinding(object source, RepeaterItemEventArgs e)
{
RepeaterItem item = e.Item;
TextBox Update_ID = (TextBox)item.FindControl("TextBoxUpdateID_Repeater");
//Button Edit_Update = (Button)item.FindControl("ButtonEditUpdate");
Button Delete_Update = (Button)item.FindControl("ButtonDeleteUpdate");
if (Social_ID == String.Empty)
{
//Edit_Update.Visible = false;
Delete_Update.Visible = false;
}
}
How can I retrieve the HTML button and hide it since it is NOT an ASP.NET button?
That button is a HTML control and will be of type System.Web.UI.HtmlControls.HtmlButton
System.Web.UI.HtmlControls.HtmlButton button = item.FindControl("ButtonEditUpdate") as System.Web.UI.HtmlControls.HtmlButton;
if(button!=null)
button.Visible = false;
In general you cannot straightly retrieve a plain-old HTML button because ASP.NET considers that as part of the text markup. Fortunately, you already added runat="server" that makes your button a server control.
The easiest way is to use an HtmlButton control. But in your markup you need the id attribute
<input type="button" name="ButtonEditUpdate" runat="server" value="Edit Update" class="ButtonEditUpdate" id="ButtonEditUpdate" />
Then in the code behind
//Button Edit_Update = (Button)item.FindControl("ButtonEditUpdate");
HtmlButton Delete_Update = (HtmlButton)item.FindControl("ButtonEditUpdate");
If you just want to set the visibility you shouldn't need to cast it.
var myButton = e.Item.FindControl("ButtonEditUpdate");
if(myButton != null)
myButton.Visible = false;
EDIT: you should give your button an ID.

How to remove row on click on confirm message true?

I have a asp gridview. On row databound I add onclick event to view item details. I have also delete button. The problem is When I click item delete, it deletes item but also redirect to item preview page. It should not do a postback and redirect
here is my code
protected void Grid_DataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Attributes["onClick"] = String.Format("location.href='" + "/Url/page.aspx?id=" + "{0}", DataBinder.Eval(e.Row.DataItem, "Id") + "'");
}
delete button
public void GvDeleteHabit(object source, CommandEventArgs e)
{
int id= Convert.ToInt32(e.CommandName);
Delete(id);
}
<asp:LinkButton OnCommand="Delete" title="Delete" OnClientClick="javascript:return confirm('Do you want to delete?')"
CommandName='<%# Eval("Id")%>' runat="server" ID="BtnDelete"></asp:LinkButton>
on client side I have confirm message. So what I'm trying to achieve is when user click delete button and Yes, I need to remove onclick event from row and delete item.
if user click No stop page from loading. so user can click somewhere on row and view details of item
Try by removing javascript: from OnClientClick. It's only needed if javascript is used in the href attribute.
The problem you're running into is that even when you click "Delete" is still registers as a click event on the row, which in turn fires off the redirect. You should put your redirect into a function, and pass in the source of the click event. If the source is your button, exit the function.
onRowClick = function(source){
if (source.element.type == "button") // this may not be correct, but you get the point
return confirm('Are you sure you want to delete this item');
//do your redirect here
}
e.Row.Attributes["onclick"] = "onRowClick(this);";
AND in your HTML markup:
<asp:LinkButton OnCommand="Delete" title="Delete" OnClientClick="javascript:return onRowClick(this);"
CommandName='<%# Eval("Id")%>' runat="server" ID="BtnDelete"></asp:LinkButton>
Since you have onclick handler on row also, you have to basically stop the event propagation on delete button click, try this it will solve the problem.
ASPX Change
<asp:LinkButton OnCommand="Delete" title="Delete" OnClientClick="javascript:return confrimDelete(e);"
CommandName='<%# Eval("Id")%>' runat="server" ID="BtnDelete"></asp:LinkButton>
Add this method in any of your js file or on the page
function confirmDelete(){
var event = e || window.event;
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
return confirm('Do you want to delete?');
}

Categories

Resources