Is it possible to access public variables declared in the code behind from a JavaScript function, e.g.
var user = <%=User%>;
Where User is declared in the code behind as:
public string User = "";
And then set in the page_load event.
<script type="text/javascript">
var userID = '<%= UserID %>';
var courseID = '<%= CourseID %>';
.... more stuff....
</script>
Then set the values on Page_Load (or in the Page_Load for the master page).
public void Page_Load( object source, EventArgs e )
{
UserID = Session["userID"];
CourseID = Session["courseID"];
...
}
hope this will help you
Related
Trying to use public properties from C# code behind and want to read the variable value from a JavaScript function
JavaScript function:
function IsAgentInProgram()
{
var optStatus = "<%=AgentOptInStatus%>";
if (optStatus == "True")
alert("You are opted in!");
else
alert ("You are opted OUT");
}
C# code behind
public bool AgentOptInStatus;
private void Page_Load(object sender, System.EventArgs e)
{
this.AgentOptInStatus = true;
}
This does not work. Output comes back as You are opted OUT. I also did an alert on optStatus and it comes back with: "<%=AgentOptInStatus%>"
Am I missing something?
You cannot read the client side variables directly in the codebehind. What you can do is creating a hidden field and setting the value with javascript, then you can read it in c#.
<asp:HiddenField ID="hdnfldVariable" runat="server" />
JS:
<script type="text/javascript">
var somefunction = function () {
var hdnfldVariable = document.getElementById('hdnfldVariable');
hdnfldVariable.value = 'value from javascript';
}
</script>
c# :
string selected = hdnfldVariable.Value.ToString();
Another option is to make an HTTP request to the server to call a function from a controller passing the data as parameters.
since i didn´t find any solution that helped me, i thought i asked.
I need a JavaScriptfunction with calls a method in my code-behind, and since i´m really new to this, i dont understand what am i doing wrong.
On my Master Page (Site.Master) i enabled PageMethods:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
And in the Content of my Page i have put the Script:
function reply_click(clicked_id) {
alert(clicked_id);
PageMethods.javascriptTest(clicked_id);
And now my method in the code-behind:
[WebMethod]
public void javascriptTest(int buttonID)
{
Test2.Text += buttonID + "***";
// Use the ID for DB access
}
I need that ID for later, when i have to do stuff in my database, but i´m always getting PageMethods undefined errors and i dont know why :/
EDIT: The Solution was indeed to make the WebMethod static, i just made a workaround, so i could use all the details i need for my db access
JavaScript:
function reply_click(clicked_id, clicked_name) {
// Schulungsdaten holen
var grid = document.getElementById("<%= SignGridView.ClientID %>");
var row = grid.rows[0];
var appointmentData = row.cells[clicked_id].innerText;
// Userdaten holen
var userID = document.getElementById("<%= UserData.ClientID %>").innerText;
PageMethods.javaScriptUserSignIn(appointmentData, userID, clicked_name, OnSucceeded, OnFailed);
location.reload();
}
function OnSucceeded(response) {
alert(response);
}
function OnFailed(error) {
alert(error);
}
Code-Behind:
[WebMethod]
public static string javaScriptUserSignIn(string appointmentData, string userID, string status)
{
string result = "";
SignIn sign = new SignIn();
result = sign.SignToTraining(appointmentData, userID, status);
return result;
}
Your javascriptTest method needs to be static
Try This:
[System.Web.Services.WebMethod]
public static void javascriptTest(int buttonID)
{
Test2.Text += buttonID + "***";
// Use the ID for DB access
}
I saw on stackoverflow we can do this to populate js variables with ViewBags (with razor):
#{
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
var userInfoJson = jss.Serialize(ViewBag.User);
}
with this:
<script>
//use Json.parse to convert string to Json
var userInfo = JSON.parse('#Html.Raw(userInfoJson)');
</script>
I want to do the same thing with aspx not razor. Can you help me?
In my controller:
Viewbag.test="Thanks to you it works!"
In my aspx:
public String test {get; set;}
protected void Page_Load(object sender, EventArgs e)
{
test = ViewBag.test;
}
<script>
alert('<%=test%>');
</script>
Result: Thanks to you it works!
Add a public property to your page and populate it on Page Load (you may have to do it on Page Init, I can't remember which processes first).
public UserType UserToSerialize {get; set;}
protected void Page_Load(object sender, EventArgs e)
{
UserToSerialize = LoadUser(); //I assume you've got some magic to do this already
}
Markup:
<script>
var userInfo = JSON.parse("<%# new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(UserToSerialize) %>");
</script>
Notice I use UserToSerialize to avoid interfering with the Page.User property.
protected void Button1_Click(object sender, EventArgs e)
{
if (count > 100)
{
StringBuilder javascript = new StringBuilder();
javascript.Append(" <script language=\"javascript\" type=\"text/javascript\">");
javascript.Append(" var tmp = confirm(\"No:Of Records exceeds 1000.Please confirm you want to continue\");");
javascript.Append("if (tmp)");
javascript.Append("{document.getElementById(\" <%=TextBox1.ClientID%>\").value=\"1\"; alert(document.getElementById(\"<%=TextBox1.ClientID %>\").value);}");
javascript.Append(" </script>");
ClientScript.RegisterStartupScript(GetType(), "recordscript", javascript.ToString(), false);
return;
}
}
Here I want to set the value of the textbox by clicking the button event and oly that condition is true.So I cant call that function from source.actually that function gets called but the textbox value doesnt set..I really dont understand where is the problem..
protected void Button1_Click(object sender, EventArgs e)
{
if(count>100)
{
StringBuilder javascript = new StringBuilder();
javascript.Append(" <script language=\"javascript\" type=\"text/javascript\">");
javascript.Append(" var tmp = confirm(\"No:Of Records exceeds 1000.Please confirm you want to continue\");");
javascript.Append("if (tmp)");
javascript.Append("{document.getElementById('" + TextBox1.ClientID + "').value=\"1\"; alert(document.getElementById('" + TextBox1.ClientID+ "').value);}");
javascript.Append(" </script>");
ClientScript.RegisterStartupScript(GetType(), "recordscript", javascript.ToString(), false);
return;
}
}
}
You need to concatenate the TextBox1.ClientID with your javascript string. The code you have will get rendered to the page as is, look at the output of your rendered page with view source, you will see the string '<%= TextBox1.ClientID =%>' not the expected ID. Keep in mind that the inline display expression <%= =%> is equivalent to a server Response.Write().
On the click of a button, I call a JavaScript function. After getting the value, I need to perform some stuff from the value obtained in the code-behind. How should I call code-behind?
My aspx:
function openWindow(page) {
var getval = window.showModalDialog(page);
document.getElementById("<%= TxtInput.ClientID %>").value = getval;
//After this I need to perform stuff 'Upload(TxtInput.value)' into database from the code-behind
}
The button calling the function is set up in the following manner:
<button class="doActionButton" id="btnSelectImage" runat="server" onclick="openWindow('../rcwksheet/popups/uploader.htm')">Select Image</button>
My desired code behind (VB):
Public Sub btnSaveImage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelectImage.ServerClick
Dim inputFile As String = Me.TxtInput.Value
//do more stuff here
End Sub
So:
Is there a way to call code-behind from the JavaScript?
Can I somehow use the "onclick" property of a button to first go to a JavaScript and then to the code-behind?
Trigger a code-behind call "onchange" of the TxtInput.Value?
yes there is a way.
first, you can use javascript to submit the form after your return value is set in TxtInput.
function openWindow(page) {
var getval = window.showModalDialog(page);
document.getElementById("<%= TxtInput.ClientID %>").value = getval;
document.forms[0].submit();
}
then in your code behind, you can handle TxtInput's value in page load event.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
if (this.Input.Value != string.Empty)
{
this.Input.Value += "blah";
}
}
}
note: you may need Identifying control that caused postback
You can put the server side code into a web service, make a service reference in an asp:ScriptManager on your aspx page and then you can call/execute the web service from javascript by calling:
WebServiceClassName.MethodName(javascriptvariable, doSomethingOnSuccess)
Here is a link on doing that:
http://msdn.microsoft.com/en-us/magazine/cc163499.aspx
You can call the __doPostBack Event.
function openWindow(page) {
var getval = window.showModalDialog(page);
document.getElementById("<%= TxtInput.ClientID %>").value = getval;
__doPostBack('btnSelectImage', getval);
}
And on the server side in your code behind, you can get the value:
In the PageLoad method:
if (Request.Form["__EVENTTARGET"] == "btnSelectImage")
{
//get the argument passed
string parameter = Request["__EVENTARGUMENT"];
//fire event
btnSaveImage_Click(this, new EventArgs());
}