asp.net methods in javascript - asp.net

I have a website
I need to find the id of my selected profile and assign that value to a variable in javascript
and show that in an alert box
where should i write the function which javascript needs to call
in the app_code folder'class
or a web page's code file
var some_variable = '<%=the_method() %>';

I'm going to assume ASP.NET WebForms and not MVC...
if you have in your page.aspx a variable named:
public string myProfile = "profile1";
you will be able to pick that up in your HTML just like anything else:
<% Response.Write( myProfile ) %>
in javascript you can do the same:
<script>
var myProfile = '<%= myProfile %>';
</script>
You can also call methods:
in your page.aspx
public string getUserName() {
return String.Format("{0} {1}", User.fname, User.lname);
}
in your javascript
<script>
var myProfile = '<%= getUserName() %>';
</script>
Remember that you need to decorate your variables and methods publicly, as if not, by default they will be private and not accessible from outside the scope of your code behind file.

You should use Webservices or Webmethods to communicate with the server side methods from your JavaScript code

Related

Call VB function from javascript

I have a javascript in my asp file where I would like to call a vb function from.
Asp javascript function:
<script type="text/javascript">
function functionName(sender, args) {
var variable = args.get_value();
PageMethods.VBFunctionName(variable);
}
</script>
Function in VB:
<System.Web.Services.WebMethod()>
Public Shared Function VBFunctionName(variable As String) As String
Dim result As String = variable
Return result.ToString()
End Function
And, I have also added the ScriptManager to enable page methods:
<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="True"></asp:ScriptManager>
But, It is not working! In the asp file, when I type 'PageMethods' the autocomplete for this option it's not available. So, I think the error is with the EnablePageMethods.
How could I resolve this problem?
The problem with your code is that you are making an Ajax call but not setting any callback to read the response from the server. You need to define a callback function (and optionally a failure function) to set what you are going to do with the response.
So your script tag should look like this:-
<script type="text/javascript">
function functionName(sender, args) {
var variable = args.get_value();
PageMethods.VBFunctionName(variable,onSuccess); //pass callback function
}
function onSuccess(response) {
alert(response); //Do whatever you wanna do with response.
}
</script>
Also, since we are working inside javascript script tag, I don't think Visual Studio will be able to suggest u the server methods.
I prefer using JQuery to call VB Function from javascript.
<script type="text/javascript">
function functionName(sender, args) {
var variable = args.get_value();
$.get( "#Url.Action("VBFunctionName")?variable=" + variable, function( data ) {
alert(data);
});
}
</script>

Setting session value in aspx page

I want to assign some value to a session variable via JavaScript in my aspx page.
var name = e.object.text;
<%# Session["CurrentName"] = name %>
Above code is giving following error:
Compiler Error Message: CS0103: The name 'name' does not exist in the current context
When I googled all the post are about getting the value from session in JavaScript. But I want to set the value to a session variable in JavaScript code.
How can I assign value to session variable in JavaScript?
Thank you
Accessing & Assigning the Session Variable using Javascript:
See Here
Assigning the ASP.NET Session Variable using Javascript:
<script type="text/javascript">
function SetUserName()
{
var userName = "Shekhar Shete";
'<%Session["UserName"] = "' + userName + '"; %>';
alert('<%=Session["UserName"] %>');
}
</script>
Accessing ASP.NET Session variable using Javascript:
<script type="text/javascript">
function GetUserName()
{
var username = '<%= Session["UserName"] %>';
alert(username );
}
</script>
Hope this helped you...! :)
You can't, at least not like this.
JavaScript is client-side thus rendered after the server-side (C#). That means you can't assign session values directly through JavaScript.
One way to solve your problem would be to use AJAX to asyncronously send a request to server and change value of the session.
Example how to do it.
<script runat="server">
var name = e.object.text;
Session["CurrentName"] = name;
</script>
Try this, by using runat="server" on script you can assign value to the Session

Embeding web service method to the .ascx(user control)

It didn't work and i think it won't but i wanted to ask you(last chance).
I have a simple ascx file. It has one select element which retrieves sub categories when it is selected (over web service).
I want to write my web method in ascx.cs file instead of to write in other asmx file.
ASCX.CS file
protected void public Page_Load(....){
//(because i can't give the ascx file path :)
TheAspxFileWhichContainsMyUserControl = Request.Url.LocalPath
}
[WebMethod]
static public string f_GetSubCats(int _iCatId){
return "<select><option value=1>One</option></select>";
}
ASCX file:
<script type="...">
$.ajax({
url: "<%=TheAspxFileWhichContainsMyUserControl%>/f_GetSubCats",
data:...
...........
success: function(msg){
// append new select to the container
}
})
</script>
you can try with this

<%# server tags in jquery

I am very new to jQuery and have got a quick question.
I wish to use my server side classes in my jQuery code, something similar to this:
$(document).ready(function() {
var temp = <%# myClass.Id %>;
})
Is this possible? if so, how?
Thank you very much
This is the later question I refined my former question to:
I'm sorry, I think I didn't explain myself too well... I've got a class name User. It's a class I built in my business logic.
I've got a web page named UserProfile, inside it I've got the following property exposing the current logged in user:
public BL.User CurrUser { get { return (BL.User)Session["currUser"]; } }I want to be able to access this User class from my aspx page using Jquery. How do I do that?
The databinding syntax
<%# MyStaticClass.MyProperty %>
will only work if you call DataBind on the container (page). What you're after is most likely the following syntax:
<%= MyStaticClass.MyProperty %>
which will also give you access to you page / control members
<%= this.MyPageProperty %>
As was already mentioned you should really assign those values to java script variables and pass those variables to you JS functions.
This will only work if your javascript is embedded in your source files (e.g. the .aspx files):
<script type="text/javascript">
var id = <%# myClass.Id %>; // store as raw value
var id_string = '<%# myClass.Id %>'; // store in a string
</script>
As others have said, if the JavaScript is in your aspx page, then using server tags will work fine.
If you have your jQuery in an external script file, then you could put this in your aspx page
<script type="text/javascript">
var myClass = $('#<%= myClass.ClientID %>');
</script>
and then use the variable in your external script file
$(function() {
myClass.click( function() { ... });
});
For other options take a look at this question and answer - How to stop ASP.NET from changing ids in order to use jQuery

How to Access ASP control located in a user control via JavaScript

Hi All,
I'm designing a user control, briefly it contains an asp:hiddenfield control, i'm going to access it via JavaScript function like this
function doAnyThing
{
var myVar = document.getElementById("myHiddenFiled");
}
but when I trace my code I found myVar assigned to null, does it matter
document.getElementById()
method is used in user control file (.ascx) or in regular (.aspx) file, taking into consideration it works in (.aspx) file correctly
You had to set by ClientID the final id of your control, that will depend by the structure of your page.
Try this:
function doAnyThing
{
var myVar = document.getElementById("<%= yourControlServerID.ClientID %>");
}
Obviously this function need to be placed in the .aspx file. I suggest you to switch to use a framework like jQuery, that allows you to retrieve controls by more sofisticate selectors. This case will be solved by:
$("[id$=yourControlServerID]");
and you can place your javascript code even in an external .js file.
to simplify you can use either:
JQuery
$("<%= yourControlServerID.ClientID %>"). ....
ASP.NET JavaScript annotation:
var myVar = $get("<%= yourControlServerID.ClientID %>");
the ASP.NET JavaScript annotation code is the same as:
var myVar = document.getElementById("<%= yourControlServerID.ClientID %>")

Resources