Adding a C# variable to javascript - c#

I have the following block of code in my header:
<script type="text/javascript">
$(document).ready(function () {
$('#target').readmytweet({
'color': 'black',
'search': 'from:' + <%= GetUserName() %>,
'user': <%= GetUserName() %>,
'width': 600,
'tweets': 10,
'speed': 25
});
})
</script>
protected string GetUsername()
{
return "somestring..";
}
However, I am getting an error message:
The Controls collection cannot be modified because the control
contains code blocks (i.e. <% ... %>).
Does anyone know how I can pass a C# variable from my code behind into this jQuery function without getting that error?
Thanks in advance

For a dynamic string:
That seems like it would work, try wrapping the code blocks with quotes, as such:
'<%= GetUserName() %>'
also you may have to use a this statement to access that method:
'<%= this.GetUserName() %>'
For a static string:
Declare your string as a public string in your aspx page:
public string UserName = "somestring..";
and access it via:
var userName = <%=this.UserName%>;

This is a well-known problem when trying to add controls to a page that contains code blocks.
A simple workaround is to use data binding expressions instead, i.e., to use <%# ... %> instead of <%= ... %>. Note that you will have to call this.DataBind(); in your Page_Load event for this to work.
(BTW, remember that the code you insert in JavaScript will need to be properly quoted.)

Accessing a server-side c# variable/property within an .aspx page.
<script type="text/javascript">
<% string username = Class.PropertName; %>
var jsUsername = '<%: username %>';
</script>

Related

DNN: HttpContext.Current.Session not Working

I'm not an expert in .NET programming and I'm trying to solve this problem but no success.
We decided to revamp our old website and part of it is to switch theme. But we have a function from old that we can't move to the new theme.
Our old website has a function that will get user's session code, so that if they move to our affiliate website via url, they will be automatically logged in.
This is the code from our old theme...
OLD THEME CODE
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="/Home.ascx.cs" Inherits="Mandeeps.DNN.Skins.Tucson.Tucson" %>
<%# Register TagPrefix="dnn" Namespace="DotNetNuke.Web.Client.ClientResourceManagement" Assembly="DotNetNuke.Web.Client" %>
<script type="text/javascript">
var onetimeurl = "<%#HttpContext.Current.Session["OneTimeURL"]%>";
$(document).ready(function() {
$('.financials_link').attr("href", "https://sub.domain.com?authToken=" + onetimeurl);
$('.financials_link').attr("target", "_blank");
var service = $.ServicesFramework(-1);
$.ajax({
type: "GET",
url: service.getServiceRoot("WebAuthModule") + "webauth/getauthtoken",
beforeSend: service.setModuleHeaders,
dataType: "json"
}).done(function(a) {
a && $(".financials_link").attr("href", "https://sub.domain.com?authToken=" + a)
});
});
</script>
It's working great. But when moved the code to the new theme, the code is not showing up and its breaking the page's layout. And I'm getting this error.
Line 20: Error BC30516: Overload resolution failed because no accessible 'ToString' accepts this number of arguments.
NEW THEME CODE
<%# Control Language="vb" AutoEventWireup="false" Explicit="True" Inherits="DotNetNuke.UI.Skins.Skin" %>
<script type="text/javascript">
var onetimeurl = "<%#HttpContext.Current.Session["OneTimeURL"]%>"; <!--LINE 20-->
$(document).ready(function() {
$('.financials_link').attr("href", "https://sub.domain.com?authToken=" + onetimeurl);
$('.financials_link').attr("target", "_blank");
var service = $.ServicesFramework(-1);
$.ajax({
type: "GET",
url: service.getServiceRoot("WebAuthModule") + "webauth/getauthtoken",
beforeSend: service.setModuleHeaders,
dataType: "json"
}).done(function(a) {
a && $(".financials_link").attr("href", "https://sub.domain.com?authToken=" + a)
});
});
</script>
Noticed on the first line, I added the control codes because that is the only thing I think is different from each other. The rest are pretty much the same.
What I've done so far is I decompiled the Home.ascx (.dll) and looked for the OneTimeURL, but I wasn't able to find it.
I wish you guys can spot the problem so I can fix this.
It seems odd to me that you are saying the old one is C# and the new one is VB??
But given what I see above, try this, just change the square brackets to parens, so the new line 20 is:
var onetimeurl = "<%#HttpContext.Current.Session("OneTimeURL") %>";
If that doesn't work, then add try adding this function at the bottom.
<script runat="server">
Public Function GetSession() As String
Return HttpContext.Current.Session("OneTimeURL")
End Function
</script>
And then line 20 would need to be:
var onetimeurl = "<%#GetSession() %>";

Call Webmethod in Usercontrol.cs from Usercontrol.ascx javascript

I have a usercontrol and in that I have a javascript function which makes a call to webmethod.
<%# Control Language="C#" AutoEventWireup="true" CodeFile="LeftMenu.ascx.cs"
Inherits="UserControls_LeftMenu" %>
<script type="text/javascript">
function GetRealTimeCount() {
PageMethods.CountOfMenus('', '', GetCountOfMenus_Success, GetCountOfMenus_Fail);
}
My webmethod code is
[System.Web.Services.WebMethod]
public static string CountOfMenus(string StartDate, string EndDate)
{
//Code here
}
But when I run the code, it gives me javascript error, CountOfMenus is undefined. I know the error is because it cant find the method in the current page but I want it to access method in the usercontrol.cs. I cant write the webmethod in every page as I have lots of pages where the usercontrol is used. Is there any way through which I can call the method of usercontrol.cs in javascript?
I solved this by below method
Javascript :
function GetRealTimeCount(StartDate, EndDate) {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "Default.aspx?Method=CountOfMenus&SD=" + StartDate + "&ED=" + EndDate;
xmlhttp.open("Get", url, false);
xmlhttp.send(null);
document.getElementById("Count").innerHTML = xmlhttp.responseText;
}
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["Method"] == "CountOfMenus")
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
GetCount(Request.QueryString["SD"], Request.QueryString["ED"]);
}
}
private void GetCount(string StartDate, string EndDate)
{
Response.Clear();
// Code to get count
Response.Write(Count.ToString());
Response.End();
}
The below link from where I got these solutions has many other options to call C# methods from javascript
http://www.morgantechspace.com/2014/01/Call-Server-Side-function-from-JavaScript-in-ASP-NET.html
when your JS code calls a PageMethod using "PageMethods." , the call does not reach the page method if it was defined in the control. The page methods in the page are only callable.
I suggest another approach, using Http Handler which is also efficient.
Try follow this post:
Call HttpHandler from javascript
Also, the following post might be useful:
http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/
Do you have ScriptManager in your UserControl Page?
if not you have to add it and set EnablePageMethods="true"
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>

Assigning C# variable value using javascript variable in code behind

I am trying to access the script variable pic and assign it to another variable in C#, say hidden field hdn. The script below is also placed on the same code behind page for some reason. I can directly access the hidden field here. But how do I assign it value from the script variable?
<script type=\"text/javascript\">
$(document).ready(function() {
$.get('<%=completeURL%>',
function(d) {
$(d).find('entry').each(function(){
var $entry = $(this);
var pic = $entry.find('content').attr('src');
alert(pic);
});
});
});
</script>
There is no way to assign a C# variable by javascript.
You have to send that value from the client (where you JavaScript is running) to the Server, and assign it.
This is so called ajax request, just google it and you'll find millions of good examples of how to achieve that.
create a hidden filed and then set the value from javascript
<asp:hiddenfield id="hf_MyValue"
value="whatever"
runat="server"/>
How To Set value in javascript
//get value from hidden filed
var test= document.getElementById('<%= hf_MyValue.ClientID %>');
//set value in hidden filed
document.getElementById('<%= hfBrand.ClientID %>').value = "True";
Create a hidden variable like this,
<input type="hidden" id="hdnVariable" runat="server" />
Now try this code
<script type=\"text/javascript\">
$(document).ready(function() {
$.get('<%=completeURL%>',
function(d) {
$(d).find('entry').each(function(){
var $entry = $(this);
var pic = $entry.find('content').attr('src');
//assign value to server side hidden variable
$("#<%=hdnVariable.ClientID%>").val(pic);
});
});
});
</script>
Now you can access this hidden field from C# code like this
string pic=hdnVariable.Value;

Pass code behind variable value to jQuery function

I am not an expert in jQuery and I am trying to pass some variable values from C# to my function called on keyup and onclick events. So far I have something like this:
$('mydiv').bind('keyup click', function(event) {}
but what I need should be:
$('mydiv').bind('keyup click', function(event, UserId, ControlId) {}
, where UserId and ControlId are some ids I am getting in code behind from the query string. I am also using jQuery 1.6.4.
How can I do this, preferably without using hidden input fields?
Thank you.
Use on instead of bind
As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.
Passing values from the server to the client with razor (if youre using asp.net mvc):
$('mydiv').on('keyup click', function(event, #UserId, #ControlId) {}
or if its webforms:
$('mydiv')
.on('keyup click', function(event, <%= UserId %>, <%= ControllId %>) {}
I would use data-attributes:
$('mydiv').data({ userId: <%= UserId %>, ControllId: <%= ControllId %> })
then you can access those data in the on click event:
$('mydiv').on('click', function(event) {
var userId = $(this).data('userId');
var ControlId = $(this).data('ControlId');
});
declare the variable as public in code behind
public string userId="abc";
Access it on client side
var uid='<%=userId %>';
$('mydiv').bind('keyup click', function(event, uid, ControlId) {}
A js file cannot directly access C# objects so you need to do something like below.
Even if you want to write complete jQuery code in your view file, you can still follow same approach.
So you can pass variables in some Model which is passed to View and once you have those variables in Model you can do something like below:
<script type="text/javascript">
var myList= #Html.Raw(Json.Encode(#Model.UsersList));
</script>
So now you have a json object which can be accessed by any individual js file as well with in same view file with the help of variable "myList".
Javascript scopes are not like scopes in other languages
so if you write
var UserId = 5;
var ControlId = 5;
$('mydiv').bind('keyup click', function(event)
{
alert( UserId );
});
it will work
check out http://jsfiddle.net/FgYTL/1/
Is my mydiv a class, id or a jQuery variable? Looks like you need to do
$('div.mydiv') or $('div#mydiv')

Class and acessibility problem c# & asp.net

i have small class like
public static class TSM
{
static string TokenID = "";
public static string GetTSM()
{
TokenID = new Guid().ToString();
return TokenID;
}
}
`GetTokenID `will return a string
i just call GetTokenID from my aspx page like
<script language="javascript" type="text/javascript">
var token= <% =TSM.GetTSM() %>;
i am getting error when i am running that aspx page.
the error is
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1002: ; expected
please guide me what is going wrong. thanks
You need to bring the namespace in which this TSM class is declared into scope in your Web Page:
<%# Import Namespace="SomeNamespace" %>
...
<script type="text/javascript">
var token = '<%=TSM.GetTSM() %>';
</script>
or fully quote it:
<script type="text/javascript">
var token = '<%= SomeNamespace.TSM.GetTSM() %>';
</script>
or include it in the <namespaces> section of your web.config.
Remark: Notice the '' around the <%=TSM.GetTSM() %> as there is no Guid type in javascript. You must use a string.
Also note that your server side code is not thread-safe because of the assignment of this static field. Also it will always generate an empty guid.
Here's how to improve it:
public static class TSM
{
public static string GetTSM()
{
return Guid.NewGuid().ToString();
}
}

Categories