asp.net passing values from JS/jquery to code behind c# - c#

I have tried "every" possible way of sending the screen.width vlaue from the JS script on the aspx page to the c# in the code behind and while I can see the screen.width being assigned correctly it never gets assigned to my hidden field value.
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:HiddenField ID="hiddenfield" runat="server" />
<script type="text/javascript" language="javascript">
$(function(){
$('#hiddenfield').val(screen.width);
});
</script>
other content
</asp:Content>
and the code behind:
protected void btnChartGo_Click(object sender, EventArgs e)
{
string s = hiddenfield.Value;
}
No matter what I try s is always ""
Something wrong with the above, everyone seems to be doing it like that and it works?

The ID of the rendered hidden field isn't "hiddenfield" - it'll be something like ctl00_bodycontent_hiddenfield.
Try using
$('[id$="hiddenfield"]')
as the selector instead.

<asp:HiddenField ID="hiddenfield" runat="server" ClientIDMode="Static">
</asp:HiddenField >
Make sure client ID mode of your hidden field is static if you are using ASP.NET 4 or use
$('#<%= hiddenfield.ClientID %>').val(screen.width);

This should get the right selector:
$('#<%= hiddenfield.ClientID %>').val(screen.width);

Check the view source of the page and find out proper id of the element and then use jquery selector over it and then at the page load check for request.form collection to check if hidden variable is coming in post request or not

Related

Passing value to the hidden field from java-script not working

This is the hidden field and the javascript.
<asp:HiddenField ID="hdn" runat="server" />
<script type="text/javascript">
document.getElementById("hdn").value = "helo";
</script>
And i tried to access the hidden field value in the .cs file as string st = hdn.value.
But it shows null when i check the value using linebreaker
Use ClientID instead of server id and also make sure that javascript is executed after the hdn field being added to DOM, you can put the script tag just before the closing body tag.
document.getElementById("<%= hdn.ClientID %>").value = "helo";
If you have .net framework 4 and above you can also set ClientIDMode to static to keep the server id on client unchanged.
HTML
<asp:HiddenField ID="hdn" runat="server" ClientIDMode="static" />
Javacript
<script type="text/javascript">
document.getElementById("hdn").value = "helo";
</script>

Can't read value from textbox into javascript variable

Hello I am trying to read a textbox(runatserver) after is gets populated form the server into a javascript variable,but it gives me a console error that "can't read form NULL" however the text box is populated by the string I want to read
this is my text box:
<form runat="server">
<asp:TextBox ID="ServerSideTextBox" runat="server" />
</form>
This is how I am populating it in C#:
ServerSideTextBox.Text= Object_JSON_Class.JSON_DataTable(dt);
it gets the right data also shows the right data string but the PROBLEM is when I try to read the value of the text box like this:
var oServerSideTextBox= document.getElementById("ServerSideTextBox");
var oServerJSON_String=eval("("+oServerSideTextBox.value+")");
I get a console error that I can't read form NULL,but the text box does have the string I want to read into javascript variable,please help
var txtToIncr = document.getElementById('<%=ServerSideTextBox.ClientID%>')
Check out this link, about reading ASP.Net controls through javascript
Try this:
var oServerSideTextBox= document.getElementById("<%=ServerSideTextBox.ClientID%>");
If that does not work, try something like this:
var oServerSideTextBox= document.getElementById("<%=ServerSideTextBox.ClientID%>_text");
Components are assigned different ID's when rendered by the client's browser. You can take a look here for more information.
put this on yout textbox ClientIDMode="Static"
Your server textbox's ID will be different if you use it in a master page structure , try finding its id.Because its actual id might be something like this ctl00_ContentPlaceHolder1_ServerSideTextbox.Check that.
Assign a class to yout textbox then try this to find the id.
$('.textbox').on('blur', function() {
var error = this.id;
alert(error);
)};
Reading the comments. I think you're referring to the wrong textbox-ID..
So I made a small test-thingy: this should work.. If not look into the source from your HTML - there you can see the ID.
<script type='text/javascript'>
function testvalue() {
var oServerSideTextBox = document.getElementById('<%=ServerSideTextBox.ClientID%>');
if (oServerSideTextBox == null) {
alert('this is null');
}
else {
alert(oServerSideTextBox.value);
}
}
</script>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="ServerSideTextBox" runat="server" Text="Testvalue" />
<input type='button' onclick='testvalue();' value='Click' />
</div>
</form>
</body>

Calling JavaScript Function From CodeBehind

Can someone provide good examples of calling a JavaScript function From CodeBehind and Vice-versa?
You may try this :
Page.ClientScript.RegisterStartupScript(this.GetType(),"CallMyFunction","MyFunction()",true);
Calling a JavaScript function from code behind
Step 1 Add your Javascript code
<script type="text/javascript" language="javascript">
function Func() {
alert("hello!")
}
</script>
Step 2 Add 1 Script Manager in your webForm and Add 1 button too
Step 3 Add this code in your button click event
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "Func()", true);
C# to JavaScript: you can register script block to run on page like following:
ClientScript.RegisterStartupScript(GetType(),"hwa","alert('Hello World');",true);
replace alert() part with your function name.
For calling C# method from JavaScript you can use ScriptManager or jQuery. I personally use jQuery. You need to decorate the method that you want to call from JavaScript with WebMethod attribute. For more information regarding calling C# method (called PageMethod) from jQuery you can refer to Dave Ward's post.
If you need to send a value as a parameter.
string jsFunc = "myFunc(" + MyBackValue + ")";
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "myJsFn", jsFunc, true);
You can not do this directly. In standard WebForms JavaScript is interpreted by browser and C# by server. What you can do to call a method from server using JavaScript is.
Use WebMethod as attribute in target methods.
Add ScriptManager setting EnablePageMethods as true.
Add JavaScript code to call the methods through the object PageMethods.
Like this:
Step 1
public partial class Products : System.Web.UI.Page
{
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static List<Product> GetProducts(int cateogryID)
{
// Put your logic here to get the Product list
}
Step 2: Adding a ScriptManager on the Page
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
Step 3: Calling the method using JavaScript
function GetProductsByCategoryID(categoryID)
{
PageMethods.GetProducts(categoryID, OnGetProductsComplete);
}
Take a look at this link.
To call a JavaScript function from server you can use RegisterStartupScript:
ClientScript.RegisterStartupScript(GetType(),"id","callMyJSFunction()",true);
Another thing you could do is to create a session variable that gets set in the code behind and then check the state of that variable and then run your javascript. The good thing is this will allow you to run your script right where you want to instead of having to figure out if you want it to run in the DOM or globally.
Something like this:
Code behind:
Session["newuser"] = "false"
In javascript
var newuser = '<%=Session["newuser"]%>';
if (newuser == "yes")
startTutorial();
You cannot. Codebehind is running on the server while JavaScript is running on the client.
However, you can add <script type="text/javascript">someFunction();</script> to your output and thus cause the JS function to be called when the browser is parsing your markup.
You can use literal:
this.Controls.Add(new LiteralControl("<script type='text/javascript'>myFunction();</script>"));
Working Example :_
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage2.Master" AutoEventWireup="true" CodeBehind="History.aspx.cs" Inherits="NAMESPACE_Web.History1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
function helloFromCodeBehind() {
alert("hello!")
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<div id="container" ></div>
</asp:Content>
Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace NAMESPACE_Web
{
public partial class History1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "helloFromCodeBehind()", true);
}
}
}
Possible pitfalls:-
Code and HTML might not be in same namespace
CodeBehind="History.aspx.cs" is pointing to wrong page
JS function is having some error
IIRC Code Behind is compiled serverside and javascript is interpreted client side. This means there is no direct link between the two.
What you can do on the other hand is have the client and server communicate through a nifty tool called AJAX. http://en.wikipedia.org/wiki/Asynchronous_JavaScript_and_XML
ScriptManager.RegisterStartupScript(this, this.Page.GetType(),"updatePanel1Script", "javascript:ConfirmExecute()",true/>
I've been noticing a lot of the answers here are using ScriptManager.RegisterStartupScript and if you are going to do that, that isn't the right way to do it. The right way is to use ScriptManager.RegisterScriptBlock([my list of args here]). The reason being is you should only be using RegisterStartupScript when your page loads (hence the name RegisterStartupScript).
In VB.NET:
ScriptManager.RegisterClientScriptBlock(Page, GetType(String), "myScriptName" + key, $"myFunctionName({someJavascriptObject})", True)
in C#:
ScriptManager.RegisterClientScriptBlock(Page, typeof(string), "myScriptName" + key, $"myFunctionName({someJavascriptObject})", true);
Of course, I hope it goes without saying that you need to replace key with your key identifier and should probably move all of this into a sub/function/method and pass in key and someJavascriptObject (if your javascript method requires that your arg is a javascript object).
MSDN docs:
https://msdn.microsoft.com/en-us/library/bb338357(v=vs.110).aspx
This is how I've done it.
HTML markup showing a label and button control is as follows.
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblJavaScript" runat="server" Text=""></asp:Label>
<asp:Button ID="btnShowDialogue" runat="server" Text="Show Dialogue" />
</div>
</form>
</body>
JavaScript function is here.
<head runat="server">
<title>Calling javascript function from code behind example</title>
<script type="text/javascript">
function showDialogue() {
alert("this dialogue has been invoked through codebehind.");
}
</script>
</head>
Code behind to trigger the JavaScript function is here.
lblJavaScript.Text = "<script type='text/javascript'>showDialogue();</script>";
ScriptManager.RegisterStartupScript(Page, GetType(), "JavaFunction", "AlertError();", true);
using your function is enough
Try This in Code Behind and it will worked 100%
Write this line of code in you Code Behind file
string script = "window.onload = function() { YourJavaScriptFunctionName(); };";
ClientScript.RegisterStartupScript(this.GetType(), "YourJavaScriptFunctionName", script, true);
And this is the web form page
<script type="text/javascript">
function YourJavaScriptFunctionName() {
alert("Test!")
}
</script>
this works for me
object Json_Object=maintainerService.Convert_To_JSON(Jobitem);
ScriptManager.RegisterClientScriptBlock(this,GetType(), "Javascript", "SelectedJobsMaintainer("+Json_Object+"); ",true);
Since I couldn't find a solution that was code behind, which includes trying the ClientScript and ScriptManager like mutanic and Orlando Herrera said in this question (they both somehow failed), I'll offer a front-end solution that utilizes button clicks to others if they're in the same position as me. This worked for me:
HTML Markup:
<asp:button ID="myButton" runat="server" Text="Submit" OnClientClick="return myFunction();"></asp:button>
JavaScript:
function myFunction() {
// Your JavaScript code
return false;
}
I am simply using an ASP.NET button which utilizes the OnClientClick property, which fires client-side scripting functions, that being JavaScript. The key things to note here are the uses of the return keyword in the function call and in the function itself. I've read docs that don't use return but still get the button click to work - somehow it didn't work for me. The return false; statement in the function specifies a postback should NOT happen. You could also use that statement in the OnClientClick property: OnClientClick="myFunction() return false;"
I used ScriptManager in Code Behind and it worked fine.
ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "CallMyFunction", "confirm()", true);
If you are using UpdatePanel in ASP Frontend.
Then, enter UpdatePanel name and 'function name' defined with script tags.
Thank "Liko", just add a comment to his answer.
string jsFunc = "myFunc(" + MyBackValue + ")";
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "myJsFn", jsFunc, true);
Added single quotes (') to variable, otherwise it will give error message:
string jsFunc = "myFunc('" + MyBackValue + "')";
You can't call a Javascript function from the CodeBehind, because the CodeBehind file contains the code that executes server side on the web server. Javascript code executes in the web browser on the client side.
You can expose C# methods on codebehind pages to be callable via JavaScript by using the ScriptMethod attribute.
You cannot call JavaScript from a CodeBehind - that code exists solely on the client.

Angle Brackets in Page head element

Iam new to ASP.NET with prev. PHP experience (which meaby is causing this problem) and Iam having small problem passing data from codebehind to view-source.
I declared string variable on codebehind side such as:
...
public string mystring = "Scotty";
protected void Page_Load(object sender, EventArgs e)
{
...
So now I want to use it in view-code but when I put it in angle brackets (<%: or <%=) and put it in head element I got no access to this value. On the other hand when I put it in BODY element everything is ok.
My failing example (simplified):
<head runat="server">
<script language="javascript">
function beamMeUp()
{
alert(<%=mystring;%>);
}
</script>
</head>
<body>
<input type="button" onclick="javascript:beamMeUp" value="Warp6" />
</body>
Can anyone explain it to me why I can't use it (the <%=mystring;%>) in HEAD but i can use it in BODY ?
Best regards
The semicolon isn't necessary when using <%=. Think of it as writing:
<% Response.Write(mystring); %>
You will want to wrap that in quotes as well.
alert("<%=mystring %>");
Without quotes would be: alert(Scotty);
which does not make much sense unless you have a javascript variable called Scotty.
It should give you an alert box showing undefined
The code-behind variable mystring is available in the <head>. C# IntelliSense isn't displaying for it since it's inside of a <script> tag.
Your problem may be that you have
<head runat="server">...
I believe this causes ASP .NET to construct an HtmlHead object which you can reference from Page.Head. However, you cannot have inline constructs such as <% .. %> and <%= %> when doing this. I believe this is also true of other ASP .NET controls such as
<asp:TreeView ...>
<asp:TreeViewItem> <%= will cause error! %> </asp:TreeViewItem
</asp:TreeView>
http://geekswithblogs.net/mnf/archive/2007/11/14/code-render-blocks-not-always-work-inside-server-controls.aspx
You really had three problems:
1.) You have a javascript error as pointed out by the first responder when he told you to use:
alert("<%=mystring %>");
2.) You have an ASP .NET error because you can't use <%= %> inside a tag that has runat="server".
3.) Another javascript error in your onclick assignment. Note it is better to wire up events in code using attachEvent and addEventListener. Your onclick assignment does not need the javascript: in front. You might do this for an href attribute, but not an onclick. In the onclick, you are already executing javascript. You could have onclick="alert('yo!')" which would work. Also, when executing a function, you must include the parenthesis, so you should have onclick="beamMeUp();" (semi colon optional).
Your revised code should look more like:
<head> <!-- notice runat="server" has been removed -->
<script type="text/javascript">
function beamMeUp()
{
alert("<%=mystring;%>");
}
</script>
</head>
<body>
<input type="button" onclick="beamMeUp();" value="Warp6" />
</body>
Note: I tried the code above and it works. I made these changes
removed runat="server" from the <head> tag
added double quotes to alert("<%=mystring;%>");
changed onclick event to onclick="beamMeUp();" NOT onclick="javascript:beamMeUp".
Good luck.

How do I get label value as a parameter into a javascript function?

Hopefully this one is not too hard to understand but I just want the label values to be inputs into a javascript function. Might be better to explain with code:
ASP.NET Label code:
<asp:Label ID="LabelCL" runat="server" Text="A single int filled in by DB"></asp:Label>
Page Source:
<span id="ctl00_cpMainContent_LabelCL">7</span>
What I would like to achieve but am not sure how to do:
<span id="ctl00_cpMainContent_LabelCL"> <script type="text/javascript">functionX(7)</script> </span>
So basically just wrap the output int in the following:
<script type="text/javascript">functionX( VALUE FROM LABEL TEXT)</script>
within the
<span></span>
Try this
<asp:Label ID="LabelCL" runat="server" />
<script type="text/javascript">
var value = document.getElementById("<%= LabelCL.ClientID %>").innerHTML;
functionX(value);
</script>
If it is called just after render you can simply use LabelCL.Text, if you need the value after and if it can be edited you can do as the exemple above.
With jQuery you can use
$("[id$=LabelCL]")
to retrieve the element.
var span = document.getElementById('ctl00_cpMainContent_LabelCL'),
text = span.firstChild;
functionX(text.textContent);
Working Demo
or if defined in the Page use script tags to render out the client id for the span using
<%= LabelCL.ClientID %>
Try this:
<asp:Label ID="LabelCL" runat="server" Text="A single int"></asp:Label>
<button onclick="displayContent(<%= LabelCL.ClientID %>)">click me</button>
<script>
function displayContent(obj) {
alert(obj.innerText);
}
</script>
You almost had it:
<asp:Label runat="server" Text="<script type='text/javascript'>document.write(functionX(7));</script>"/>
Use this piece of code
onclick="myFunction(labelName.innerText)"

Categories