Clearing hidden input fields after postback - c#

I use hidden input fields to pass values form my javascript to the code behind. This works great but when I try to clear the fields from the code behind this doesn't work.
<input type="hidden" id="iRowNumberTblOne" name="iRowNumberTblOne" value="" runat="server"/>
I tired to do it by a few ways but they all don't work.
This is the easiest way and most logic but it doens't want to clear the values
iRowNumberTblOne.Value = "";
I even made a javascript, so the values would be cleared on the client side.
The alert comes up the first time "at startup" but after a postback it seems like the code behind doesn't find the javascript again.
<script type="text/javascript">
function clearInputFileds() {
alert('test');
document.getElementById("ctl00_contentHolder_iSiteAlias").value = "";
document.getElementById("ctl00_contentHolder_iServiceName").value = "";
document.getElementById("ctl00_contentHolder_iRowNumberTblOne").value = "";
document.getElementById("ctl00_contentHolder_iRowNumberTblTwo").value = "";
}
</script>
This is the code I use in the codebehind
Page.ClientScript.RegisterStartupScript(GetType(), "", "clearInputFileds();", true);
Do you have any idea why these methods doesn't work? Maybe know a better way to clear this fields?
EDIT:
The input fields get filled by a javascript function. This function gets runs onClick.
function setClickedValues(siteAlias, serviceName, rowNumberTblOne, rowNumberTblTwo) {
document.getElementById("ctl00_contentHolder_iSiteAlias").value = siteAlias;
document.getElementById("ctl00_contentHolder_iServiceName").value = serviceName;
document.getElementById("ctl00_contentHolder_iRowNumberTblOne").value = rowNumberTblOne;
document.getElementById("ctl00_contentHolder_iRowNumberTblTwo").value = rowNumberTblTwo;
}

This can be done in the code behind. But it is important to do it at the right time in the ASP.Net Application Livecycle. Take a closer look at:
ASP.NET Page Life Cycle Overview
Understanding ASP.NET View State
Usually you (re)set the value in the click event handlers of your submit button or in the LoadComplete event. If you do it before, the value will be overwritten at the time the ViewState is restored.
The following image is extremly usefull when working with ASP.Net pages and ViewState:
(Source: http://msdn.microsoft.com/en-us/library/ms178472%28v=vs.100%29.aspx)
BTW: It is a very bad idea to reset the value in client code with hard coded ID's as they are subject to changes.

Since all of those are server-side elements (you have them as runat="server") the easiest way to clear the values is simply to do:
elementID.Value="";
On all of them after postback. If you are saying that the values are not being cleared after doing the above, it's probably because you are not checking if(!IsPostback) before executing the function that populates the values in the first place.
Your client side code should also work but it's probably failing because your last parameter to the RegisterStartupScript is true, which indicates that the <script> tags ought to be added. This may cause a problem because your function is already enclosed in <script> tags so the last true parameter is not needed in this case.

Related

How can I call a Javascript function multiple times from C# Code-Behind? It's only executing once

I am working on a project at the moment, for which I will need to call JavaScript functions with multiple parameters from C# Code-Behind as the controls are being created dynamically(in code-behind).
I decided to open up a new project just to test a basic JavaScript and it's functionality with just one parameter to see if it would work but I was very unsuccessful even with that.
I have tried to read many other answers I found online, including here on stackoverflow ofcourse. Most just tell me that I have to give each textbox an ID or that I must change the "key" attribute in the registerclientscriptblock and registerstartupscript methods, both of which I have tried without any success. I guess there could be something wrong with my JavaScript function as well, which is not my forte(heard the word in a movie, love it, not the movie though). Please help me if you can and want to.
What I am doing is creating some textboxes, giving them ID's and passing the client IDs as the parameter in the JavaScript function, which is supposed to simply change their background colors and text colors.
What's happening is that only one of the textboxes(the last one inserted into the function) is showing changes made from the JavaScript, but of course I want all of them to be showing these changes.
Here is the Script:
The only reason I put added window.onload is because before this I was getting null exceptions. I'm sure there is a better, perhaps correct, way of doing this but I don't know it.
Here is the Code-Behind and the Result/Output of the program:
Here, Problem is you write "window.onload". You have to remove from your code.
You can do like this.
1) Put script in Head.
<script type="text/javascript">
function call(id) {
var field = document.getElementById(id);
field.style.color = 'red';
field.style.backgroundColor = 'yellow';
}
</script>
2) Create form in body.
<form runat="server">
<div id="text" runat="server"></div>
</form>
3) Put c# code in Page_Load method.
for (int i = 0; i < 5; i++)
{
TextBox tb = new TextBox();
tb.ID = "textbox" + i;
tb.Text = "Textbox"+i;
panel.Controls.Add(tb);
text.Controls.Add(panel);
ClientScript.RegisterStartupScript(this.GetType(), "textbox" + i, "<script>call('textbox" + i + "');</script>", false);
}
Is this Clear? If you have any question. Let me know.

Setting Content in RadEditor

I have visited the Telerik's website and viewed their demos etc...
But I am having problems trying to load content (html) in the RadEditor.
I have a Button_Click event where I get my html string and then set it to the RadEditor. The RadEditor is inside a RadWindow and only becomes visible when the button is clicked.
protected void btnSubmitHtml_Click(object sender, EventArgs e)
{
RadEditor1.Content = "<p>hello there</p>";
RadWindow1.Visible = true;
}
This doesn't show the html inside the RadEditor for some odd reason. I suspect it is the page life cycle that is involved with this problem.
Are there any suggestions to solve this?
I have encountered this problem multiple times and never found a "Proper" resolution.
However, a great work around is to simply set the content from the clientside via injected script. The end result is the same, and if you can tolerate the 10 millisecond delay, worthy of consideration.
EDIT after comment requested reference
Basically all you need to get an instance of the editor using ASP.NET WebForms $find function. That takes the html ID of the root of the rendered object and returns the client side viewModel if one exists.
The $(setEditorInitialContent) call at the end assumes that jQuery is present and delays the execution of the function till page load.
<telerik:radeditor runat="server" ID="RadEditor1">
<Content>
Here is sample content!
</Content>
</telerik:radeditor>
<script type="text/javascript">
function setEditorInitialContent() {
var editor = $find("<%=RadEditor1.ClientID%>"); //get a reference to RadEditor client object
editor.set_html("HEY THIS IS SOME CONTENT INTO YOUR EDITOR!!!!");
}
$(setEditorInitialContent);
</script>
Take a look here to see how to get a RadEditor to work in a RadWindow: http://www.telerik.com/help/aspnet-ajax/window-troubleshooting-radeditor-in-radwindow.html.
Said shortly, here is what you need to have in the OnClientShow event of the RadWindow:
function OnClientShow()
{
$find("<%=RadEditor1.ClientID %>").onParentNodeChanged();
}
To edit Html code only you can add -
EnableTextareaMode="true"
Add this property to the RadEditor.
I suspect that the way the control tries to interpret the html might be one of the problems. The other thing that may be causing this problem is the page life cycle.

Preventing Over Posting in ASP.NET Webforms

I know this is a basic question, but I am curious as to what the different options are, and what the best practice would be.
If I have a form that is responsible for saving reservations into a system, how can I prevent the form from being posted twice if the user hits the button twice really quickly?
I know there are a few ways in which I can accomplish this, but I am not quite sure which is the standard way of preventing this. Partially because I am new to web forms, and am used to dealing with MVC.
Thanks ahead of time.
I've used two approaches to this problem:
Use a token based approach. Each page has a hidden input with the current random token. This token is also stored in the user's session. Once the postback occurrs, I compare tokens and, if they are valid, generate a new session token and continue processing. When the second postback occurs, the token no longer matches and prevents processing.
Use javascript to disable the submit button. If you take this approach, and need the button event handler to fire, you'll need to create a hidden input with the name attribute of the button before submitting. The hidden input is required because disabled inputs do not end up in the post data.
I would recommend a client-side onClick event handler that disables the button or makes it invisible, preferably the latter, and replace the button with a label that reads "Processing..." or something like this
I have been using something like this when using an asp:Button for submitting:
1) Set the submit button's UseSubmitBehavior="false"
2) Set the submit button's OnClientClick="pleaseWait(this, 'Please Wait...');"
3) Include javascript code in the page:
function pleaseWait(obj, message) {
if (typeof(Page_ClientValidate) == 'function') {
if (Page_ClientValidate()) {
obj.disabled = true;
obj.value = message;
return true;
}
}
return false;
}
This solution is nice because it is simple but still accounts for client-side javascript validations. It isn't perfect, because it still relies on Javascript, which could be turned off, but that's unlikely to be done by someone who doesn't have the sense to click once and wait for a response. :)
Easy way - use the ajax AnimationExtender control.http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/Animation/Animation.aspx
Simply attach the extender to the button and add a disable action.
<asp:Button ID="CopyScenarioButton" ClientIDMode="Static" OnClick="CopyScenarioButton_Click"
OnClientClick="setTimeout( function() {$('#CopyScenarioButton').attr('disabled', 'disabled');},0)"
EnableViewState="false" Text="Save New Scenario" ToolTip="Save New Scenario"
CssClass="btnNormal" runat="server" />
or the later version that includes some validation first:
function PreSaveHybrid() {
var doSave = PreSave();
if (doSave !== false) //returns nothing if it's not a cancel
setTimeout(function () { $('#btnSave').attr('disabled', 'disabled'); }, 0);
return doSave;
}

Ajax removes any changes made my javascript

Using ajax I am causing an OnTextChangedEvent before this happens there is some Javascript that performs a check on the input field for validation and outputs some text based on whether it is valid or not. The Ajax I run resets the changes made by my javascript. It all happens in this order:
Javascript fires!
Text changes show
Ajax fires!
Text changes reset
The ajax partial autopostback is contained in an update panel. Without giving any code away is there anyone who has an idea of a way to stop the javascript changes resetting?
Over the day I will add code as I find time. Thought I would get the question up atleast. Thanks in advanced.
The Text changes are made in the DOM-Model and are not transmitted to the server.
If the ajax fires it will override the changes in the DOM made by javascript.
Solution is to transmit the validation-texts to the server and to add them again via ajax.
An UpdatePanel completely replaces the contents of the update panel on
an update.
This means that those events you subscribed to are no
longer subscribed because there are new elements in that update panel.
Full answer here
In your Page or MasterPage, put the following script
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function EndRequestHandler(sender, args)
{
Validate(); //method that performs check on input field
}
</script>

calling javascript function on selected index change of select input type in ASP.NET

Is there a way to call a javascript function when the selectedIndex of a select input has been changed?
Using this code in the c# code behind file
riskSeverityDropDown.SelectedValue = Convert.ToString(planRisk.Severity);
riskSeverityDropDown.SelectedIndexChanged += new EventHandler(riskSeverityDropDown_SelectedIndexChanged);
riskSeverityDropDown.AutoPostBack = true;
want to change something else on the page with javascript when the index is changed.
Any help would be much appreciated.
Thanks in advance
You're already going to server code (AutoPostBack is true), which means you're going to rebuild the entire page anyway. Running javascript at this point would be a little silly, because any changes you make to the DOM will be lost and any ajax requests you want to send can instead be handled by normal server code. If you really want to do this, you can just register the script to run when the page loads after the postback.
On the other hand, if you can do this without any server code at all then set AutoPostBack to false and the basic html select control has a nice onchange event you can handle.
Simply add an onchange to your asp:dropdownlist.
<asp:DropDownList ID="riskSeverityDropdown"
AutoPostBack="True"
SelectedIndexChanged="riskSeverityDropDown_SelectedIndexChanged"
onChange="functionName()"
runat="server" />
or to do this from codebehind use:
riskSeverityDropdown.Attributes["onchange"] = "functionName()";
You want to add an attribute to that drop down called "onchange" and set it to call a JavaScript method of your choosing.
Use JQuery. It exposes a rich set of events that you can use to code against practically anything in a uniform manner. It is also quite easy to learn, compact, and popular.
In short you can't go wrong if you use JQuery. It is meant to solve problems like this well.

Categories

Resources