I am taking over a project in which a client has some annoying issues.
They have a dropdown that autopostbacks on change to place the selected text into a t-sql query. Any value that has an apostrophe is causing an query error due to not being escaped
I do not have access to compiled code, but was hoping to write a quick band-aid fix to on selected changed, before posting replace an apostrophe to a double apostrophe to escape it as it goes into query.
I wrote a javscript ddl.change function that works at changing the text.
This however is not working even though the apostrophe does change into two. I was wondering if someone could help understand why.
I have two thoughts of scenarios causing the issue.
On autopostback, it triggers before javascript change function does, therefore passing the original value before javascript has a change to modify it.
The server side code only understands what it originally placed into the dropdown and therefore no matter how much I manipulate the client code, it will only see what it placed?
Can anyone confirm either of these scenarios?
Help would be appreciated!
EDIT: I REVERSE ENGINEERED THE CODE, YES ITS VERY UGLY (AND SQL INJECTABLE) BUT IS NOT MINE AND I CANNOT MODIFY IT
C# Code
protected void ddls_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.ddls.SelectedIndex == 0)
{
this.pnlA.Visible = false;
}
else
{
this.pnlA.Visible = true;
string text = Common.GetSql("~/Sql/" + this._Conn + "/PropertyAddressReverseSearch.sql", false, true).Split(new char[]
{
Conversions.ToChar(this._Delimiter)
})[4];
text = string.Concat(new string[]
{
"SELECT * FROM (",
text,
") a WHERE StreetName='",
this.ddls.SelectedItem.Text,
"' "
});
this.Bind(this.ddla, text);
this.ddla.Items.Insert(0, new ListItem("I'm not sure of the house number...", Conversions.ToString(-1)));
this.ddla.Items.Insert(0, new ListItem("", Conversions.ToString(0)));
this.map.Visible = false;
}
}
Javscript + Control
<asp:dropdown runat="server" id="ddls" autopostback="true">
<script type="javascript/text">
$(document).ready(function() {
$("select[id$='adsearch_ddls']").change(function() {
var ddlsValue = $("select[id$='adsearch_ddls'] option:selected").text();
ddlsValue = ddlsValue.replace(/'/g,"\'\'");
$("select[id$='adsearch_ddls'] option:selected").text(ddlsValue);
return false;
});
});
</script>
You can not modify (or add/remove) the Select/dropdown list items client-side, and simply get the same server-side items, with ASP.NET Webforms when viewstate is enabled.
Unless you send back the modified items in another way, like for example in this answer where list items are copied to a hidden field:
function SaveList()
{
//Clear the hidden field
var hField = document.getElementById('<%= YourHiddenField.ClientID %>');
hField.value = '' ;
var selectedList = document.getElementById('<%= YourDropDownList.ClientID %>')
for(i = 0; i < selectedList.options.length; ++i)
{
hField.value = hField.value + ',' + selectedList.options[i].value;
}
That is, assuming by "On selected index change calls server side code" you mean a postback is triggered?
Disabling the ViewState will cause other problems (like SelectedIndexChanged not triggering, etc).
You could handle the selection change through your own (AJAX) postback. But the difference between server- and client-side list items would still remain.
Related
I have a class derived from WebControls.TableCell.
When the Text property is set, I call a method that dynamically adds asp:Panels and asp:LiteralControls to the Cell. I want to reference these controls in Javascript, so naturally I tried using the ClientId of the panels in my JS functions. However, these controls have no ClientId set (the string is empty). Why is this? How do I force the ClientIds to be set?
As a temporary solution, I set the ClientIDMode to "static" and created the IDs on my own, but this is not satisfactory because it's hard to reference those IDs in JS. Why? If you assign, for example, "12345" to one control, it gets changed on client side to something like "MainContent_123456". This is bad because the "MainContent" part is not fixed; thus I never know for sure what the real Id on the client side will be. Currently, I can get the control with jQuery using $ctrl = $('[id$='12345']');, but this is dirty because it would get any control that has '123456' in its id.
So, back to the original question: how do I get my ClientIds set automatically for my panels in my custom TableCells?
Edit: Code added
protected void Page_Load(object sender, EventArgs e)
{
this.ClientIDMode = System.Web.UI.ClientIDMode.Static;
}
Code in the method that adds the controls to the custom TableCell:
Panel remainingTextPanel = new Panel();
remainingTextPanel.ID = Guid.NewGuid().ToString();
remainingTextPanel.Style["display"] = "none";
LiteralControl remainingText = new LiteralControl(myText.Substring(initialStringLength, myText.Length - initialStringLength));
remainingTextPanel.Controls.Add(remainingText);
this.Controls.Add(remainingTextPanel);
Panel linkBtnPanel = new Panel();
LinkButton lnkBtn = new LinkButton() {Text = "...", OnClientClick = "toggleDynamicText('" + remainingTextPanel.ID + "'); return false;" };
lnkBtn.Font.Bold = true;
linkBtnPanel.Controls.Add(lnkBtn);
this.Controls.Add(linkBtnPanel);
And the JS Code:
function toggleDynamicText(id) {
$ctrl = $('[id$=' + id + ']');
$(document).ready(function () {
$ctrl.toggle(1000);
});
}
Without seeing any code it's difficult to say what's going on but to access your controls using jQuery you can do the following:
$("#<%=myElement.ClientID%>")
This way it doesn't matter what .NET assigns as the ID.
I have a textbox with a live search function. It is working all good except one problem. If I type any characters on it, it just loses its focus. If I set textbox.Focus(), the cursor goes at the beginning of the textbox.
I have tried most of solutions on the internet. Please check my codes below.
asp:TextBox ID="searchCompany" runat="server" Text="" CssClass="searchCompany" AutoPostBack="true" Width="190px" OnTextChanged="searchCompany_TextChanged"></asp:TextBox>
In page_Load
protected void Page_Load(object sender, EventArgs e)
{
//ScriptManager1.RegisterAsyncPostBackControl(Menu1);
menuDisplay();
searchCompany.Attributes.Add("onkeyup", "setTimeout('__doPostBack(\\'" + searchCompany.UniqueID + "\\',\\'\\')', 0);");
//searchCompany.Attributes.Add("onfocus", "javascript:setSelectionRange('" + "','')");
//searchCompany.Focus();
}
and I have tried javascript as below
<script type="text/javascript">
function setSelectionRange() {
var inputField = document.getElementById('searchCompany');
if (inputField != null && inputField.value.length > 0) {
if (inputField.createTextRange) {
var FieldRange = inputField.createTextRange();
FieldRange.moveStart('character',inputField.value.length);
FieldRange.collapse();
FieldRange.select();
}
}
}
</script>
I have tried to put codes on a method "searchCompany_TextChanged" which is calling if user type any characters on a textbox everytime however it is not working as well.
I saw other solutions with using Textbox.Select() but System.Windows.Control is not working in asp.net i guess.
Any idea??
There's a very simple trick that's worked for me. Basically, set the text value of the of input to itself to its own text value, and that will move the cursor to the end of the text. Then just focus it. This code uses jQuery to demonstrate that, but you should be able to do that in straight JS as well.
HTML
<input type="text" id="focusText"></input>
<button id="focusButton">Set Focus</button>
JavaScript
$("#focusButton").click(function() {
var text = $("#focusText").val();
$("#focusText").val(text).focus();
})
Here's a non jQuery example of the JavaScript, HTML should be the same:
document.getElementById("focusButton").onclick = function() {
var inputElement = document.getElementById("focusText");
var text = inputElement.value;
inputElement.value = text;
inputElement.focus();
}
Here's a fiddle demonstrating the non-jQuery version of the code: http://jsfiddle.net/C3gCa/
I have some 32 TextBoxes and 1 "Save" button. What I want is to save the text for only those TextBoxes which have their Texts changed. How can I achieve that? How do I know the text of which TextBoxes have changed?
Personally, I would do it server-side. Assuming you have no data binding involved, you could do something like the following in your ASPX.CS code-behind:
...
private string InitialValue1
{
get { return ViewState[#"IV1"] as string; }
set { ViewState[#"IV1"] = value; }
}
// Repeat for all 32 text boxes.
protected void Page_Load( object sender, EventArgs e )
{
if(!IsPostBack )
{
TextBox1.Text = InitialValue1 = loadText1FromDatabase();
// Repeat for all 32 text boxes.
}
}
protected void MySaveButton_Click( object sender, EventArgs e )
{
if ( TextBox1.Text!=InitialValue1 ) saveText1ToDatabase( TextBox1.Text );
// Repeat for all 32 text boxes.
}
...
Of course, in a real-world-scenario, I would do some looping/array handling instead of writing 32 same functions/properties.
I would recommend using a jQuery function on load to make a fake old data input.
Something like this:
$(document).ready(function (){
$(":text").each(
var newid=$(this).attr("id") + "_old";
var oldvalue=$(this).val();
var formy=$("form");
formy.appendChild("<input type='hidden' name='" + newid +"' value='" + oldvalue +"'>);
})
This way, if you change the number, the function automatically writes the correct number for you.
Then on the server side you can compare the values with something like below :
var inputs = Request.Form.Keys.Where(rs=>rs.Contains("_old"));
foreach (var input in inputs)
{
//check the _old vs the input without the old and do your thing
}
You can detect this on the client side for keypress, or compare the values on post and send over a list of items that changed.
However if you want to do this on the server side, you will have to load up your server data and manually compare it against every textbox.
Use session variables to store the data for every postback and compare the values. If the value of a certain textbox changes then save that otherwise dont save.
You can do using HiddenFields. on page load you can set HiddenFields with original TextBox values.
on save button you can compare HiddenFields value with TextBox value, If HiddenField value does not
match with TextBox value then you can save that TextBox value in DB otherwise not.
Use cookie variables to store the data for every postback and compare the values.
Which version are you using, In case of 3.5 and above i would request you to check on this IPostBackDataHandler. This should help you in achieving what you want.
In previous versions i think you will have to do it only by comparing it with the original text or the least you could use the MERGE keyword
(you will have to modify your db queries) while you are pushing your records into the database.
i have about 4 textboxes on my webpage...some are asp:textboxes while others are input type="text".
the input textbox is populated through a javascript popup calender control while asp.net textbox is populated by typing. The initial values of these textboxes are retrieved from a database.
When a user changes these values, they are not saved and the textboxes are cleared out after the submit button is clicked. Please help resolve this confusion. Thanks.
thanks for your reply but it is still not working.....
i have put this code in my page load event
if (Page.IsPostBack)
{
if (ViewState["stock"] != null)
TextBoxMaterial.Text = ViewState["stock"].ToString();
if (ViewState["supplier"] != null)
TextBoxSupplier.Text = ViewState["supplier"].ToString();
if(ViewState["matTime"] != null)
TextBoxMatTime.Text = ViewState["matTime"].ToString();
if(ViewState["prodTime"] != null)
TextBoxProdTime.Text = ViewState["prodTime"].ToString();
if (ViewState["shipTime"] != null)
TextBoxShipTime.Text = ViewState["shipTime"].ToString();
if(ViewState["cmr"] != null)
cmrDue.Value = ViewState["cmr"].ToString();
if(ViewState["kc"] != null)
kcDue.Value = ViewState["kc"].ToString();
}
and also put the below code in the onclick event for the button
ViewState["stock"] = TextBoxMaterial.Text;
ViewState["supplier"] = TextBoxSupplier.Text;
ViewState["matTime"] = TextBoxMatTime.Text;
ViewState["prodTime"] = TextBoxProdTime.Text;
ViewState["shipTime"] = TextBoxShipTime.Text;
ViewState["cmr"] = cmrDue.Value.ToString();
ViewState["kc"] = kcDue.Value.ToString();
string prodLine = DDProdLine.SelectedValue;
string stock1 = DDMaterial.SelectedValue;
string stock2 = ViewState["stock"].ToString();
string supplier = ViewState["supplier"].ToString();
string billet = RBBillet.SelectedValue;
string matTime1 = ViewState["matTime"].ToString();
string matTime2 = DDMatTime.SelectedValue;
string prodTime1 = ViewState["prodTime"].ToString();
string prodTime2 = DDProdTime.SelectedValue;
string shipTime1 = ViewState["shipTime"].ToString();
string shipTime2 = DDShipTime.SelectedValue;
CultureInfo cultureInfo = CultureInfo.CurrentCulture;
string format = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern.ToString();
string cmr = ViewState["cmr"].ToString();
string kc = ViewState["kc"].ToString();
string x = cmr.Substring(3, 2);
string y = cmr.Substring(0, 2);
string z = cmr.Substring(6, 4);
string x1 = kc.Substring(3, 2);
string y1 = kc.Substring(0, 2);
string z1 = kc.Substring(6, 4);
string finalCmr = x + "/" + y + "/" + z;
string finalKC = x1 + "/" + y1 + "/" + z1;
DateTime dt = DateTime.ParseExact(finalCmr, format, cultureInfo);
DateTime cr = DateTime.ParseExact(finalKC, format, cultureInfo);
string custDate = dt.ToString("dd/mm/yyyy");
string kcDate = cr.ToString("dd/mm/yyyy");
string id = Request.QueryString["id"];
bool success = true;
TextBoxProdComment1.Text = stock2 + "," + supplier + matTime1 + "," + prodTime1 + "," + shipTime1 + "," + custDate
+ "," + kcDate;
try
{
success = CRTopButtons.SaveProdTable(id, prodLine, stock1, supplier, billet, matTime1, matTime2, prodTime1,
prodTime2, shipTime1, shipTime2, custDate, kcDate);
}
catch (Exception e)
{
TextBoxProdComment2.Text = e.Message;
System.Diagnostics.Trace.Write(e.StackTrace);
}
the textboxes still clear out and none of it is readonly..........
please help
I had a similar problem and The Solution to "Losing data changed by javascript during postback"
is best described by this article
ViewState and Readonly Property of Textbox
for example let's say we have this asp.net control:
<asp:TextBox ID="txtName" runat="server" EnableViewState= "false" ReadOnly="true" />
if you change the value of this control through javascript in the client side it will not be propagated via postback in the serverside...whatever you do with javascript unless you remove readonly="true". Now there is a solution to this problem as described in the article above.
Simply put this in the PageLoad event
if (!IsPostBack)
txtName.Attributes.Add("readonly","readonly");
and you're done. Just don't forget to remove ReadOnly="true" or Enable="false" if your intent was to disable the control from editing just use the snippet above. Don't forget to remove Enable="false" if you put it on.
Another thing I ran into... If you're using an ASP.NET TextBox Control (for example), and it's READONLY or DISABLED, the postback won't catch the changed value.
Per my issue, I was changing the value of the control thru javascript and even though the browser rendered the change, on the postback, the control still retained the original value.
Seems a common problem too... javascript kicks off a custom ASCX calendar control and result is injected by javascript, into the textbox. Users shouldn't be allowed to directly modify textbox value...
string strDate = Request.Form["id_of_input_element"].ToString();
I ultimately used the above to um, "reset" the control, after the postback, to it's changed value!
The <input> textboxes won't save their state after postback. ASP.NET does not handle that for you.
If you put code in your Page_Load event to set the values of the ASP.NET textboxes, the values that were posted back will not be saved, because Page_Load happens after the child control states are restored in the ASP.NET page lifecycle. The values are already restored by ASP.NET, but you are overwriting their restored values.
The correct thing to do to fix #2 is to check Page.IsPostBack before loading your initial state, like this:
if ( !Page.IsPostBack )
{
// set the textbox initial states from the database
}
UPDATE:
There are two ways to solve problem #1. One thing you could do is to use the Request.Form[] collection to retrieve the posted back value manually, like this:
string strDate = Request.Form["id_of_input_element"].ToString();
The other thing you could do, and this is what I'd recommend if you can, is to change the <input> element to an ASP.NET textbox, and hook up any client-side Javascript events to that. Then ASP.NET will completely handle your postback.
i found this when looking for an answer to the same type of problem and now that i found my problem i thought it could help someone else putting it here.
in my case i had a tag <form> inside the <form> of my controls, so, if you didnt resolve your problem with above i sugest search for a <form> lost inside your <form>.
hope it helps for some cases.
If I get you're asking for right, I think you're trying to make those textboxes readonly. If so, I had this problem before and solved it by making the textboxes readonly using C# not ASP.NET, I just added lines like textboxName.Attributes.Add("readonly", "readonly"); in the Page_Load and it worked just fine. This solution I found here on Stackoverflow
instead of TextBoxPassword.Text=Password
use
TextBoxPassword.Attributes["value"]=Password
It seems that your viewstate is disabled. Enable the viewstate in Page directive.
So I now have the following jquery to hide or show a textbox based on specific values selected in a DropDownList. This works except that I need the first display of the popup to always be hidden. Since no index change was made in the drop down list, the following does not work for that. If I code it as visible="false", then it always stays hidden. How can I resolve this?
<script language="javascript" type="text/javascript">
var _CASE_RESERVE_ACTION = "317";
var _LEGAL_RESERVE_ACTION = "318";
function pageLoad() {
$(".statusActionDDLCssClass").change(function() {
var value = $(this).val();
if (value == _CASE_RESERVE_ACTION || value == _LEGAL_RESERVE_ACTION) {
$(".statusActionAmountCssClass").attr("disabled", false);
$(".statusActionAmountCssClass").show();
}
else {
$(".statusActionAmountCssClass").attr("disabled", true);
$(".statusActionAmountCssClass").hide();
}
});
}
</script>
Thank you,
Jim in Suwanee, GA
If you set
visible=false
.Net will not render it. You can do
style="display:none;"
and .Net will render the tag properly but CSS will hide it from the user.
Add the following to pageLoad function
function pageLoad(sender, args) {
$("input.statusActionAmountCssClass").hide();
.... rest of code .....
}
By the way, I would recommend using the selector $("input.statusActionAmountCssClass") to get a jQuery object containing a reference to your input, otherwise jQuery will search all elements to match the CSS class .statusActionAmountCssClass
EDIT:
Another change that could also be made is to use jQuery's data() to store the two global variables
$.data(window, "_CASE_RESERVE_ACTION","317");
$.data(window, "_LEGAL_RESERVE_ACTION","318");
then when you need them simply cache the value in a local variable inside the function
function someFunctionThatNeedsGlobalVariableValues() {
var caseReserveAction = $.data(window, "_CASE_RESERVE_ACTION");
var legalReserveAction = $.data(window, "_LEGAL_RESERVE_ACTION");
}
this way, the global namespace is not polluted. See this answer for more on data() command