Javascript send innerHTML to server ASP.NET - javascript

I have an issue regarding some interaction between Javascript and ASP.net control.
In javascript I get the innerHTML of a content editable like this :
var text = document.getElementById('corps').innerHTML;
document.getElementById('corpsToServer').value = text;
document.getElementById('callingServer').click();
This call an action on a click event for an ASP.NET updatePanel that call the serveur side of my application :
<form id="Form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel runat="server">
<br />
<asp:TextBox CssClass="serveurNeeded" runat="server" ID="corpsToServer" ClientIDMode="Static" ></asp:TextBox>
<br />
<asp:TextBox CssClass="serveurNeeded" ID="recup" runat="server" ClientIDMode="Static">
</asp:TextBox>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="callingProlexis" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</div>
<asp:Button CssClass="serveurNeeded" ID="callingProlexis" runat="server" OnClick="tryReturn"
ClientIDMode="Static" Text="callhim" />
</form>
Then the call is like this :
<script language="C#" type="text/C#" runat="server">
public void tryReturn(object sender, EventArgs e)
{
prolexisIMPL proxy = new prolexisIMPL();
string getCorpsText = corpsToServer.Text;
string retourTest = proxy.tryThis(getCorpsText);
recup.Text = retourTest;
UpdatePanel1.Update();
ScriptManager.RegisterClientScriptBlock(this, GetType(), "mykey", "afterServerReturn();", true);
}
</script>
I have figure that it is the passing of innerHTML that make me get an error 500 from the server. Some post told that it is a validation issue to prevent injection from user side, but configuring the :
ValidateRequest="false"
is a bad idea and does not work.
How can I manage to send my innerHTML to the server side without this error showing up ? Something Like him pretending it's just a string and the tag are just part on the string, not html or javascript injection.
Configuration are ASP.NET MVC 4.0 without code behind, Vanilla Javascript, IE5.
EDIT : the error :
Sys.Webforms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was : 500

You have several solutions :
Encode HTML client side
The cleanest one is to encode your html before sending it to the server. You can do it easy with jQuery, but in javascript you will have to create you own encoding method. You can see an example here : http://www.yuki-onna.co.uk/html/encode.html
Disable Validation
You can disable the server validation, either placing the ValidateRequest="false" in your page header or placing it in the web.config file (very dangerous, because it will be applied on all your website).
This solution is not secure if you store the HTML data for display it in another page, because some users of your application will be able to send dangerous content that will be displayed in the browser of other users.

use encoder.js for encoding html to safe scripts and then send to asp.net. You have to ValidateRequest="false" along with that.
You can get examples here.

Related

How to get client side value from server side using VB.NET?

I have an ASPX page where I set data with JS but I am having a bad time trying to get this data from VB.
This is a simplified version of what I have...
ASPX:
<body onload="DoStuff();">
<script>
function DoStuff() {
var myvalue = document.getElementById('lblValue');
myvalue.textContent = "blah";
console.log (myvalue.textContent); // just to be sure that the value IS there
}
</script>
<div style="display:block">
<asp:label id="lblText" visible="true" runat="server">Text: </asp:label><asp:label id="lblValue" runat="server" visible="true" ></asp:label><br /><br />
<asp:label id="lblMsg" visible="true" runat="server" >Message: </asp:label><asp:label id="lblMsgValue" runat="server" visible="true" >Click button...</asp:label><br /><br />
<asp:Button id="btnGo" Text="Go" OnClick="btnGo_Click" runat="server"/>
</div>
</body>
ASPX.VB:
Protected Sub btnGo_Click(sender As Object, e As EventArgs)
lblMsgValue.Text = "The value is *" & lblValue.Text & "*"
End Sub
I am always getting nothing as output. Any idea?
How interesting. I had NEVER noticed that a label set client side does NOT persist.
Note that if you use code behind, set a label.Text, then the label DOES persist and survive a round trip. However, setting the label in JS? Well, you see the browser udpate instant, but when you post back, you lose that text.
This means you need to use say a text box - they DO persist, and even when changed client side.
So, for example this code:
<asp:Button ID="Button2" runat="server"
Text="Js Code" Width="114px"
OnClientClick="setlabel();return false" />
<br />
<asp:Label ID="Label1" runat="server" Text="a" ClientIDMode="Static" ViewStateMode="Enabled"></asp:Label>
<br />
<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static"></asp:TextBox>
<script>
function setlabel() {
vlable = document.getElementById("Label1");
vlable.innerHTML = 'Hello how are you';
vtextBox = document.getElementById("TextBox1")
vtextBox.value = "Js setup text box"
}
</script>
So, after we run the above button (js), then both the text box, and the label will update and you see the results in the browser.
However, now drop in another button like this:
<asp:Button ID="Button1" runat="server" Height="26px" Text="Set Lable" Width="129px" />
And code behind:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Debug.Print(Label1.Text)
Debug.Print("Text box = " & TextBox1.Text)
End Sub
Output (after running client side js button).
a
Text box = Js setup text box
So we see the Text="a" of the label, while it did change in the browser, when we post back, it does not survive WHEN changed client side.
As noted, if code behind changes a label - it does persist, and does survive around trips. But the label does not.
However, a text box, or hidden field and most controls that show/have the ability to hold data or a value will survive - labels are just not one of those controls.

How to run javascript using server side code in ASP.Net Web Form application in update panel?

I want to use some javascript code inside update panel in ASP.Net web form application using serverside code. The problem is the following code only works if i used it outside update panel but not works inside, even with alert.
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" Text="Server" OnClick="Button1_Click"/><br />
<asp:Button ID="Button2" runat="server" Text="Cleint" OnClientClick="alert('Hello World(Cleint)')"/>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
Code Behind
protected void Button1_Click(object sender, EventArgs e)
{
this.ClientScript.RegisterStartupScript(this.GetType(),
"ShowMessage", string.Format("<script type='text/javascript'>alert('{0}')</script>",
"Hello World (Server)"));
}
when running this application only the Client Click event works but not the server side event. However when removing update panel ant try again both events work.
I searched a lot and found some similar questions but all answers didn't work. I just wanna to fix problem for the example i put above. Thanks
Try to replace your code behind in the button click event with this:
ScriptManager.RegisterStartupScript(this, this.GetType(), this.ClientID, string.Format("alert('{0}')", "Server"), true);
Hope this helps.

Data from entity framework displayed in javascript/Jquery dialog

I have a problem, and looking for a solution for 2 days
Target : Create/edit client... in HTML build a dialog with and asp fields with clientIDMode static
<div id="divDialog" runat="server" clientidmode="Static" style="display: none;">
<div class="DialogFields">
<asp:Label ID="Label1" runat="server" Text="Firstname"></asp:Label>
<br />
<asp:TextBox ID="tbxFirstName" runat="server" ClientIDMode="Static"></asp:TextBox>
</div>
...
In script
$("#btnShowDialog").click(function () {
openDialog();
});
function openDialog() {
$("#divDialog").dialog('open');
$("#divDialog").parent().appendTo($("form:first"));
}
When I click the button btnShowDialog it works fine... But
Beneath it I have a gridview within it a edit button (asp:Linkbutton) with a event to the codebehind it looks like:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Edit" OnCommand="Edit_Click" CommandArgument='<%#Eval("RelationID") %>'
runat="server"><img src="../images/Edit-item.png" alt="Edit" /></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
In codebehind take the parameter from commandargument and fire LoadInfo (specific data to all the fields in de dialog).
LoadInfo(e.CommandArgument != null ? int.Parse(e.CommandArgument.ToString()) : -1);
but no way I get the dialog open.
I tried
ClientScript.RegisterStartupScript(this.GetType(), "Popup", "openDialog();", true);
and
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "openDialog();", true);
after this LoadInfo, push btnShowDialog button and it opens the dialog and all data perfect in place.
Also tried the other way around as Directly to Jquery function, get all data loaded and open the dialog. 2 problems, loading in codebehind was not even started before the dialog opens. and I only can get a static function in the codebehind.
A lot of ground to cover for me, but can any body help me out (even for a part).
...Thanx
If I understand your question correctly, you are trying to fire some client scripts (openDialog) from the server side, but they wont fire?
Try placing your page in an update panel, lets assume that we name the update panel "MyUpdatePanel". And then refer to the update panel like this:
ScriptManager.RegisterStartupScript(MyUpdatePanel, MyUpdatePanel.GetType(), "MyUpdatePanelScript", "openDialog();", true);

ASP.Net get ScriptManager.RegisterClientScriptBlock return on UpdatePanel hiddenField

I am trying to obtain the return of a Javascript function that I call ont server side using ScriptManager.RegisterClientScriptBlock .
Currently, my javascript function save the value in a HiddenField that is contained in an UpdatePanel. When I call the method , I run the ScriptManager.RegisterClientScriptBlock and after that get the value of the HiddenField , but always returns me the value of the previous call. Here I show the code:
My User Control ASPX Side:
<script>
var num = 0;
function getReturn() {
num = num + 1;
var hr= document.getElementById('<%= hdf.ClientID %>');
hRetorno.value = num;
}
</script>
...
<asp:UpdatePanel ID="up1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:HiddenField ID="hdf" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
My User Control Server Side Code:
public String GetReturn()
{
return MyControl.jsGetReturn(this.Page, this.hdf);
}
private static String jsGetReturn(Page page, HiddenField hid)
{
ScriptManager.RegisterStartupScript(page, page.GetType(), "key", "getReturn();", true);
return hid.Value;
}
Index Page ASPX Side:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div style="width:720px; height:480px;">
<uc1:MyControl runat="server" id="MyControl1"/>
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="btn" runat="server" OnClick="btn_Click" />
<asp:TextBox ID="txt" runat="server" ></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
Index Page Server Side Code:
protected void btn_Click(object sender, EventArgs e)
{
txt.Text = MyControl1.GetReturn();
}
You can not do these things simultaneously.
Set value of hidden field from server side code using javascript via RegisterClientScriptBlock or RegisterStartupScript.
And retrieve that hidden filed value in server side code at the same time.
This is because, (changed) hidden field value is available to server-side code only when there is postback, when you set the value from server-side, there is no postback happening, that is why you are always getting previous value , i.e. that old value which is posted back to page.
EDIT
When you invoke RegisterClientScriptBlock or RegisterStartupScript, it won't make JS call instantly, rather it just append a javascript call before or after <form.. tag based on what you used and they are called on document load, so that means in jsGetReturn when you call RegisterStartupScript, it will set value of hidden field in document load, - hid.Value will not have updated value, as it is yet to be incremented via document load.

Javascript-error on finding object

im stuck with Javascript in Asp.net...
I made a TextBox named tbValidFrom and another named tbValidTo.
I also made two ModalPopups.
Then i try to open the ModalPopupExtenders when the TextBoxes get focus:
<script type="text/javascript">
$('#tbValidTo').focus(function () {
$find('ModalPopupExtenderNV1').show();
})
$('#tbValidFrom').focus(function () {
$find('ModalPopupExtenderNV2').show();
})
</script>
but it doesnt finds tbValidTo or ModalPopUpExtender ?
Runtime-Error in Microsoft JScript: Object expected
Here is one of the two ModalPopupExtenders and TextBoxes:
<asp:TextBox ID="tbValidFrom" runat="server"></asp:TextBox>
<asp:UpdatePanel ID="UpdatePanelNV2" runat="server" RenderMode="Inline" UpdateMode="Conditional">
<ContentTemplate>
<cc1:ModalPopupExtender ID="ModalPopupExtenderNV2" runat="server" TargetControlID="HiddenField6"
PopupControlID="PanelNewVersion" BackgroundCssClass="modalBackground" BehaviorID="ModalPopupExtenderNV2"
Enabled="True" />
<asp:HiddenField ID="HiddenField6" runat="server" />
</ContentTemplate
</asp:UpdatePanel>
The same as above is with the other ModalPopupExtender and TextBox...
Help would be really nice.
Thanks
Edit: Yes i use a masterpage!
Fails where it is marked yellow.
your jQuery syntax is wrong.
change your script to:
<script type="text/javascript">
$('#tbValidTo').focus(function () {
$(this).find('#<%=ModalPopupExtenderNV1.ClientID%>').show();
});
$('#tbValidFrom').focus(function () {
$(this).find('#<%=ModalPopupExtenderNV2.ClientID%>').show();
})
</script>
elements that has runat="server" will eventually end with a different ID than you entered in the aspx file.
i used the <%= %> to get the 'final' id.
hope that helps
Seeing that markup there is two chances for the issues.
With the ModalPopupExtender.
Where you have given the panel "PanelNewVersion" . Seems like its missing in the markup.
In the Javascript code. If you want to hide that Popup, give the name of the panel. NOt the name of the ModalPopupextender.
Also you have given an update panel there in page, so you can easily handle the modalpopup in any srever side event of your textbox.
Otherwise, if you want to use the Modal popup ijn client side, use jQuery Modalpopup. That will the better option.
ASP.NET Can modify the ID's of elements, if you use a Masterpage the element id's will be modified to something like the following : ctl001_ContentPlaceHolder1_tbValidFrom
To get around this ASP.NET modification of your elements you can use ASP.NET Inline Expressions to get the rendered ID from the object.
See the answer to the following question for more information on ASP.NET Inline Expressions
You can look at changing the Client ID Mode (The way ASP.NET Modifies IDs when the page is rendered) here :
ASP.NET Client ID Modes
EDIT :
The AjaxControlToolkit's ModalPopupExtender is not rendered on the page as a html element, therefore you cannot find this item using the ClientID of the ModalPopupExtender.
You must use the BehaviourID to call the show function on.
The below code should work correctly :
$('#<%= tbValidTo.ClientID %>').focus(function () {
$find('ModalPopupExtenderNV1').show();
})
$('#<%= tbValidFrom.ClientID %>').focus(function () {
$find('ModalPopupExtenderNV2').show();
});
This will find the textbox object using the ASP.NET Inline expressions to find the client ID and will then find the behaviour ID and execute the Show method.
Example Markup :
<script type="text/javascript">
$(document).ready(function() {
$('#<%= tbValidFrom.ClientID %>').focus(function () {
$find('ModalPopupExtenderNV2').show();
});
});
</script>
<asp:TextBox ID="tbValidFrom" runat="server"></asp:TextBox>
<asp:UpdatePanel ID="UpdatePanelNV2" runat="server" RenderMode="Inline" UpdateMode="Conditional">
<ContentTemplate>
<cc1:modalpopupextender id="ModalPopupExtenderNV2" runat="server" targetcontrolid="HiddenField6"
popupcontrolid="PanelNewVersion" backgroundcssclass="modalBackground" behaviorid="ModalPopupExtenderNV2"
enabled="True" />
<asp:HiddenField ID="HiddenField6" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Panel ID="PanelNewVersion" runat="server">
testing panel
</asp:Panel>

Categories