0

My website is on WPF project. I want to pass a string from my cs file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    public string strHello = "Hello World!";
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

To my website:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html>
<head id="Head1" runat="server">
<script type="text/javascript">var jsstrHW = '<%=strHW%>'; alert("jsstrHW = " + jsstrHW);</script>
</head>
<body>
</body>
</html>

The output from alert method:

jsstrHW = <%=strHW%>

Please guide me how to do it right. Thanks a lot, Orian.

EDIT: I tried:

ScriptManager.RegisterStartupScript(this, this.GetType(), "someID", "alert('This pops up');", true);

and it didn't work as well. I copied only my aspx file and his cs file to other folder, then I closed my solution and created new one with those files. Everything worked on Google Chrome! So.. my code is probably right, but something in my solution ruin my website. what can it be? As I said before - I need that website for WPF app and not for Google Chrome (or Mozilla Firefox, etc.).

Thanks again, Orian.

Orian Zinger
  • 87
  • 1
  • 2
  • 11
  • why are you passing like this? – dazzling kumar Nov 17 '14 at 09:53
  • Possible duplicate [passing variable values from c# to javascript](http://stackoverflow.com/questions/20849272/passing-variable-values-from-c-sharp-to-javascript) – Izzy Nov 17 '14 at 09:55
  • dazzling kumar, I searched passing variables from cs to js and i found that. lzzy, i'm not using a seperate js file so it's not a duplicate, but i'll try to use the serialize way and RegisterClientScriptBlock way. – Orian Zinger Nov 18 '14 at 10:37

3 Answers3

0

You access the c# variable in JS like this

<script>
     var jsstrHW = "<%=this.strHello %>";
     alert("jsstrHW = "+jsstrHW);
</script>

Here strHello is the variable name on cs page.

Suggestion you can use RegisterClientScriptBlock

Update you can try like this

 <script>
      var jsstrHW = <%= "'" + strHello + "'"%>;
     alert(jsstrHW);
</script>
yogi970
  • 446
  • 5
  • 14
0

You can use REGISTERCLIENTSCRIPTBLOCK to pass the value from C# to javascript.

C# code:

ScriptManager.RegisterClientScriptBlock(Me.Page, Me.Page.GetType(), "someID", 
                     "PassValue("+ strHW +");", True)

Javascript code:

function PassValue(value) 
{
    alert(value)
}
Saravana Kumar
  • 3,669
  • 5
  • 15
  • 35
0

Well, Eventually I found another way to pass strings:

  this.WPFWindow.InvokeScript ("WriteFromExternal", new object [] {"this string is passed to  WriteFromExternal"});

and in JS:

function WriteFromExternal(message)
    {
        alert("Message from C#: " + message);
    }

And it worked :)

Thank you all.

Orian Zinger
  • 87
  • 1
  • 2
  • 11