InnerHtml in c# - c#

I have <td id="StatusPreview" runat="server"></td> and it gets populated by a js function by:
document.getElementById('StatusPreview').innerHTML = Ext.getCmp('TYComboEdit').getRawValue();
Now, I would like to change the content of the td in c# when a button is clicked.
I created the following method:
protected void hiddentoggletofrenchBackend(object sender, DirectEventArgs e)
{
this.StatusPreview.InnerHtml = "aaaaa";
}
It does not change the content on the td. However, if I place an alert after setting the InnerHtml it alerts aaaaa even though the td content has not changed to reflect this. If I place an alert before setting the InnerHtml the alert is blank.
How can I change the InnerHtml of the div?
Thank you!
UPDATE:
If I change the html to <td id="StatusPreview" runat="server">q</td> the alert shows q if it is placed before setting InnerHtml, and switches to aaaaa if placed after.
It is as if InnerHtml is taking the value on pageload, not the current value.

To update an ASP.NET control during a DirectEvent, you should call the .Update() method.
protected void hiddentoggletofrenchBackend(object sender, DirectEventArgs e)
{
this.StatusPreview.InnerHtml = "aaaaa";
this.StatusPreview.Update();
}

Adding runat=server to a td element turns it into a HtmlTableCell control. The relevant property to set the inner text on this control is InnerText.
As this is a server side control, any change is only going to happen after postback to the server. That would mean the entire page is reloaded and re-rendered. You can examine requests to the server and the server responses with the free tool Fiddler. Assuming a postback is actually happening, are you sure you're not overwriting the new inner text with JavaScript which runs on page load?
Do you even need to do a postback for this? If "aaaaa" is not a placeholder for what will become a database or some other lookup, I would render the alternate text into a hidden div or into some JavaScript and do the text change entirely in JavaScript.

Related

Why label text is getting changed after clicking on asp.net button?

I have a WebForm ASP label and button. I am setting the label's value on page load. For example, the label text on page load is 2 items selected. This comes from the database. Then if the user changes the selection then it counts the selected values by jQuery and sets the text as 5 items selected.
When I click on the submit button to save changes, again it resets to 2 items selected. I didn't use an update panel. I don't know what is going on here. Can anyone please explain this scenario?
$("#lblCount").text($('#grdProducts').find('input#chkSelect:checked').length + ' Complementary Products added');
C# on page load:
lblCount.Text = ComplementaryproductCount.ToString() + " Complementary Products added";
I do not understand why the label text is changed on button click. I couldn't find anything while debugging too.
Thanks
When you set lblCount.Text in your code, that value is set into the ViewState of the page... that means when your page is posted back to the server (to handle an event, etc) ASP.Net knows what lblCount.Text was originally and can re-render the HTML with the same value.
As part of that post-back to the server, the browser will send back that ViewState along with any input control values (things like textboxes, dropdowns, hidden field).
What it does NOT do is post-back any changes you might have made to the elements on the page via things like jQuery (other than input controls I mentioned above).
The result is that although you've changed the element on the screen, the server knows absolutely nothing about that change, and it will re-send the original HTML for the label back to the browser.
Your only option is to do something as suggested by #John in his comment... you need to store the fact the element has changed in an input, and then use that.
For instance...
<asp:Label runat="server" id="lblCount" />
<asp:HiddenField runat="server" id="hdnCount" />
function updateCount(newCount) {
$("#<%=lblCount.ClientID%>").text("Count: " + newCount.toString());
$("#<%=hdnCount.ClientID%>").val(newCount.toString());
}
Then in your code-behind you can have...
if (!Page.IsPostBack)
{
var count = 1;
lblCount.Text = String.Format("Count: {0}", count);
hdnCount.Value = count.ToString();
}
else
{
lblCount.Text = String.Format("Count: {0}", hdnCount.Value);
}

Get onload hidden field value using c#

I am using the below code to assign the value to a hidden control.But in code behind i can't get the value of the hidden control. Please help me to get this.I tried more time.
Script
=======
<script type="text/javascript">
function load_value() {
var val = document.getElementById('<%= hf_xml.ClientID %>');
val.value= "hai";//Whatever i want
alert(val.value);//alert message show with text hai
}
window.onload = load_value;
</script>
<asp:HiddenField ID="hf_xml" runat="server" />
Code Behind
===========
protected void Page_Load(object sender, EventArgs e)
{
string value = hf_xml.Value;//Always Empty
}
There is nothing really missing/incorrect in your code. Try to understand the sequence of events that happen.
Window.Onload is expected to get executed when the Page finishes loading. Whereas Page_Load is expected to be called earlier as the Page is still under process.
And this is indeed happening. As verified using debug symbols, the Page_Load is called first and the window.onload method will be called later. This is why your HiddenField is showing empty value.
Also, as expected, for the very first time when page is requested, HiddenField value will be Empty, but on next postback onwards, Value will be set for this HiddenField.
You should not use innerHTML on input controls
Use value instead
var val = document.getElementById('<%= hf_xml.ClientID %>');
val.value = "hai";//Whatever i want
are you trying to get the value before posting to server ?? means you cant access the value before posting to server(means on button click or some server side events)
put a asp:button on form and check the value after clicking the button

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.

Ajax AsyncFileUpload fires server code but does not update client web page

I have an asyncfileupload control inside an update panel. The file succesfully upload and fires the correct server side code. The code on the server is exected as expected however, one line in the server code changes the text on a label. I step through the code in debug mode and the line is executed but no change is made to the page.
Here's some of the code:
<asp:UpdatePanel runat="server" ID="updater" >
<ContentTemplate>
<asp:AsyncFileUpload ID="fileUpload" runat="server" OnUploadedComplete="FileUploadComplete" />
<asp:Label ID="AsyncText" runat="server" Text="File Type not checked" />
</ContentTemplate>
</asp:UpdatePanel>
public void FileUploadComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
System.Threading.Thread.Sleep(500);
if(fileUpload.HasFile) { AsyncText.Text = "file of correct format: "; }
}
Can anyone help me with solving this problem or offering annother solution??
Thanks
I think you are going to have to move toward a different solution. From your label message, it looks like you are trying to check the file type, correct? Basically, the AsyncUplaod control, although posting back to get the uploaded file to the browser, is not actually updating the page's viewstate, thus the label never gets updated. Boo! I was able to visualize this using this code in the page load event.
if (Page.IsPostBack)
{
if (Request.Files.Count > 0)
{
AsyncText.Text = "file of correct format";
ListItem item = new ListItem("item to add");
lb.Items.Add(item);
}
}
This was allowing me to set the label text but still nothing changed until I clicked on a random button that I added to the page. This button didnt even have an event in the code behind, but it was enough to cause a normal postback, and the label text and list item were successfully updated/added to the list. With that said, I would wait to update any labels until the user clicks upload by using a seperate upload button. (ie use the AsyFileUplaod to get it to the browser, but another button to save the file to the server). You can always do file evaluations in the button click event by referencing the posted files to the webpage as I did in the code above.
Some other examples I found online were using javascript to change the label text which works well also. Somthing like this:
string message = "";
if (e.StatusMessage == "Success")
{
message = "File upload successful;";
}
else
{
message = "File did not upload successfully;";
}
ClientScript.RegisterStartupScript(this.GetType(), "akey", "document.getElementByID('label').value =" + message, true);
Another example: here
I think in this case it's just the nature of the control and the only way to achieve what you want is though some creative thinking. If you have any other questions about anything I listed here feel free to ask.
Good luck!
Where is the label positioned, inside or outside the update panel? Seems like the partial page update may not be including the update to the label text. I would say move the label around as the simplest suggestion, but you could also try something like RegisterStartupScript which will change the lable text via javascript. This should still give you server side control over what text to display based on what happens during the upload.
If you could post some code that would be great.

How do I generate JavaScript during an AJAX callback (postback) and then execute it on the browser?

In summary:
I have an ASP.NET web page that causes an AJAX postback to the server. When this event handler runs (in the code behind) it will generate some JavaScript that I then want to run in the client. Not sure how to achieve this.
In Detail:
I have an ASP.NET web page with multiple items displayed on the page.
As a "nice to have", I want to display either a green circle or a red cross next to each item (these differ depending upon each item). Since it isn't vital for the User to see these icons and also because it takes several seconds to work out which icon should be shown for each item, I want to perform this after the page has loaded, so in an AJAX callback.
My thought therefore was this. When creating the page, I would create both icons next to each object and create them with the style of "hidden". I would also make a note of each one's client ID.
Then, when the callback occurs, I fetch the necessary data from the database and then create a JavaScript function that changes the display for each of the icons I want to show from "hidden" to "visible".
I thought I could achieve this using the ScriptManager object.
Here's a very trivial version of my server side code (C#)
void AjaxHandler(object sender, EventArgs e)
{
// call to database
string jscript = "alert('wibble');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "uniqueKey", jscript);
}
Obviously, here I'm just trying to get an alert to fire after the postback has occurred...in real life I'd have my JavaScript function to change the display of all the icons I want to display.
When I run this, the serverside code runs and yet nothing happens in the server.
I have also tried:
ScriptManager.RegisterClientScriptBlock()
Page.RegisterStartupScript()
Page.RegisterClientScriptBlock()
Page.ClientScript.RegisterStartupScript()
Page.ClientScript.RegisterClientScriptBlock()
but none of them work....
FireFox shows the following JavaScript error:
Error: uncaught exception: [Exception... "Node cannot be inserted at the specified point in the hierarchy" code: "3" nsresult: "0x80530003 (NS_ERROR_DOM_HIERARCHY_REQUEST_ERR)" location: "http://localhost/MyWebSiteName/Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=ctl00_RadScriptManager1_TSM&compress=1&_TSM_CombinedScripts_=%3b%3bSystem.Web.Extensions%2c+Version%3d3.5.0.0%2c+Culture%3dneutral%2c+PublicKeyToken%3d31bf3856ad364e35%3aen-US%3a3de828f0-5e0d-4c7d-a36b-56a9773c0def%3aea597d4b%3ab25378d2%3bTelerik.Web.UI%2c+Version%3d2009.3.1314.20%2c+Culture%3dneutral%2c+PublicKeyToken%3d121fae78165ba3d4%3aen-US%3aec1048f9-7413-49ac-913a-b3b534cde186%3a16e4e7cd%3aed16cbdc%3a874f8ea2%3af7645509%3a24ee1bba%3a19620875%3a39040b5c%3af85f9819 Line: 1075"]
Does anyone know if what I am trying to do is even allowed?
If not - what's my alternative?
Thank you
Since your script doesn't have enclosing <script> tags, you need to use this form of RegisterStartupScript:
ScriptManager.RegisterStartupScript(this, this.GetType(), "uniqueKey", jscript, true);
You said your initial goal was:
The idea was that the page would load, data would be sent (AJAX) to the server. The server would then generate some JavaScript based upon this data and send that back to the page. That JavaScript would then run updating the page in a specific way.
Here's a way you can do that:
given:
<asp:ScriptManager runat="server" ID="scriptManager">
</asp:ScriptManager>
<script type="text/javascript">
function endRequestHandler(sender, args) {
var dataItems = args.get_dataItems();
for(var key in dataItems){
if(/^javascript:/.test(dataItems[key])){
eval(dataItems[key].substring("javascript:".length));
}
}
}
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
</script>
<asp:UpdatePanel runat="server" ID="pnl">
<ContentTemplate>
<asp:Button runat="server" ID="btnClick" Text="Click me!" OnClick="btnClick_Click" />
</ContentTemplate>
</asp:UpdatePanel>
You can create a click handler that does this:
protected void btnClick_Click(object sender, EventArgs e)
{
ScriptManager.GetCurrent(Page).RegisterDataItem(this, "javascript:alert('hello world!');");
}
What's happening is during the postback, the page request manager is sent a data item your code-behind. That data-item happens to be a javascript command. After the postback, the client side script manager's endRequest handler is checking for data items. Normally you'd want to see who those items are for, which is apparent by the key of the item (it's the client ID of the control that is the target of the data being sent). In your case, you could load this up with the javascript that you want to fire, tell yourself that it's a javascript because it's prepended, then dynamically evaluate the script.
So in this example, clicking the "Click Me!" button will generate a Hello World prompt whose script was actually created by the code-behind during the postback.
You'll have to be very cautious with this approach until you're comfy - I'd avoid references to "this"...
Happy coding.
B
Okay
The idea was that the page would load, data would be sent (AJAX) to the server. The server would then generate some JavaScript based upon this data and send that back to the page. That JavaScript would then run updating the page in a specific way.
Couldn't get that to work....
I got around this in the following way:
When the page loads, data is sent (AJAX) to the server. This processes the data and serialises the results updating a hidden text element, which goes back to the browser. Meanwhile, I have a JavaScript timer on the page that runs a JavaScript function that was generated when the page first loads. This function looks at the hidden text element. If that element has text (the result of the postback) then it shuts down the timer, deserialises the data and then works out how to update the page.

Categories

Resources