I have an ASP script that checks the username of the authenticated user, now I want to pass the username of the authenticated user into a javascript variable/string
ASP:
<%
Function isAuthorized()
Dim ipos
Dim ustring
Dim uname
Dim ilngth
ustring = Request.ServerVariables("AUTH_USER")
ipos = Instr(ustring, "\") + 1
ilngth = Len(ustring) + 1
uname = Trim(Mid(ustring, ipos, ilngth - ipos))
End Function
%>
Javascript:
<script>
var chk = <%uname%>;
alert(chk);
</script>
How can I make this work correctly and where in my code exactly do these elements go?
Set a property to get the username: eg in c#
Public string Username{ get { return Page.User.Identity.Name;} }
Call this in JavaScript using <%=Username%>
Try this:
<script>
var chk = "<%= uname %>";
alert(chk);
</script>
Related
I have the following case where a user has selected a product, the product record has been retrieved and the backorder flag is set. I want to ask the user if the want to include it in the order anyway. I can't seem to find an exaample anywhere that demonstrates it in an IF statement.
My VB Code Snippet:
Dim backorder = myDataTable.Rows(0)("backorder").ToString()
If backorder = "True" And <somehow ask user it they want to order anyway> Then
'do something
End If
My Javascript in aspx file:
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Selected item is on temporary back order. Do yuou want to include it on this order?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
I can read the variable being added, by javascript, to the page from VB, but can't figure how to call the javascript in order to prompt the user.
For some reason I can't get my head around this. Please advise with example.
Use the RegisterStartupScript method:
Sub ProcessOrder()
'Your code to process the selected products here...
Dim orderAnyway As string = hdnConfirmResponse.Value.Trim()
If selectedItem.BackOrdered Then
If orderAnyway = "" Then
Dim cs As ClientScriptManager = Page.ClientScript
' Define the name and type of the client scripts on the page.
Dim csname1 As String = "ConfirmScript"
Dim cstype As Type = Me.GetType()
' Check to see if the startup script is already registered.
If (Not cs.IsStartupScriptRegistered(cstype, csname1)) Then
Dim cstext1 As String = "Confirm();"
cs.RegisterStartupScript(cstype, csname1, cstext1, True)
End If
Else
If orderAnyway = "yes" Then
'ADD THE BACKORDERED ITEM SINCE THEY CONFIRMED
End If
End If
End If
End Sub
I hate answering my own question but this what finally worked. Mixture of mjw's answer and more research on my javasvript attempt. Rather than have JS create the hidden field, I added it to the HTML
<asp:HiddenField runat="server" id ="confirm_value"/>
New VB:
If myDataTableFrame.Rows.Count > 0 Then
Dim backorder = myDataTableFrame.Rows(0)("backorder").ToString()
If backorder = "True" And confirm_value.Value <> "Yes" Then
Dim cs As ClientScriptManager = Page.ClientScript
' Check to see if the startup script is already registered.
If (Not cs.IsStartupScriptRegistered(Me.GetType(), "ConfirmScript")) Then
Dim cstext1 As String = "Confirm();"
cs.RegisterStartupScript(Me.GetType(), "ConfirmScript", "Confirm();", True)
End If
Return
Else
confirm_value.Value = "No"
...
New Javascript:
See ASP.NET set hiddenfield a value in Javascript Also added a reclick of the button if they answered "OK"
<script type = "text/javascript">
function Confirm() {
if (confirm("Selected item is on temporary back order. If you want to include it on this order click OK, then resubmit it?")) {
//had to resort to this to find hidden field rather than document.getElementById('confirm_value')
var x = document.getElementById('<%= confirm_value.ClientID%>');
x.value = 'Yes';
//re-click the button
document.getElementById('<%=bttnadd.ClientID%>').click();
} else {
var x = document.getElementById('<%= confirm_value.ClientID%>');
x.value = 'No';
}
}
</script>
in my .aspx page I've got something like this- I create dynamically javascript variables which look like this
var region11 = ''
var region12 = ''
So when I click on a region of svg I get the id of the region which is for example 11 and I should set the href property region11 variable.
Unfortunately the javascript debbuger says that it cannot find region variable
<% var regions = ICYGEN.MRF.Data.CityData.SelectProvinces(); %>
<% foreach (ICYGEN.MRF.Data.Entities.Region region in regions)
{ %>
var region<%= region.RegionID %> = '<%= MRFUrlHelper.Elections2015_RegionUrl(region.RegionID,region.Title, 1026) %>';
<% } %>
jQuery(window).load(function () {
var svgMap = jQuery('#svg-map').contents().get(0);
alert(region11);//it's Ok here and it finds it
jQuery('svg path', svgMap).click(function () {
var ids = String(this.id);
location.href = region+ids; //can not find
You're using region instead of region11 in your click event handler:
location.href = region+ids; //can not find
Change to:
location.href = region11+ids; //can not find
Or I suppose:
location.href = region<%= region.RegionID %>+ids; //can not find
I am retrieving the color of the html anchor control on the server side. following is my tried code
Design:
<a id="lkdelete" onclick="SingleDel(this);" runat="server" style="font-weight:bold ">Delete</a>
Javascript:
function SingleDel(ctrl)
{
var row=ctrl.parentNode.parentNode;//to get row containing image
var rowIndex=row.rowIndex;//row index of that row.
var hsingle_del=document.getElementById('<%hsingle_del.ClientId %>');
hsingle_del.value=rowIndex;
var modalPopupBehaviorCtrl = $find('bmpe');
modalPopupBehaviorCtrl.set_PopupControlID("pnlPopup");
modalPopupBehaviorCtrl.show();
}
Vb.Net:
Dim pid As String = ""
For Each r As GridViewRow In gridview.Rows
Dim lnk As HtmlAnchor = CType(r.Cells(1).FindControl("lkdelete"), HtmlAnchor)
If lnk.Style("Color") = "Red" Then
pid = CType(r.FindControl("lblposid"), Label).Text
End If
Next
here at 1st row of gridview the color is red . but it returns "". any solution?
make few changes on your code. add a hidden field on your page.
function SingleDel(ctrl)
{
var rowIndex=ctrl.offsetParent.parentNode.rowIndex-1;
var hsingle_del=document.getElementById('<%=hsingle_del.ClientId %>');
hsingle_del.value=rowIndex;
var modalPopupBehaviorCtrl = $find('bmpe');
modalPopupBehaviorCtrl.set_PopupControlID("pnlPopup");
modalPopupBehaviorCtrl.show();
}
vb(instead of for loop)
pid = CType(gridview.Rows(hsingle_del.Value).FindControl("lblposid"), Label).Text
I want to access the value of an application variable in JavaScript. How can I do that?
Declare a public property in codebehind.
public string firstName = "Sanju";
Access this in JavaScript like this.
<script>
var myName;
function GetMyName()
{
myName = <%=this.firstName%>
}
</script>
To Access value in Session State, use this.
myName = '<%=Session["firstName"]%>'
To Access value in Application State, use this.
myName = '<%=Application["firstName"]%>'
You can make the variable public to access in javascript.
In code behind.
public string YourVar = "hello";
In javascript
alert("<%= YourVar %>");
Note the value of the server side variable is substituted in generated html / javascript once the response is sent. If you want to access it from javascript after page is loaded then you might need to use ajax call to fetch value from server.
The following gets the ClientID of the rendered control
//markup
<asp:TextBox ID="aTextBox" runat="server" />
<asp:TextBox ID="bTextBox" runat="server" />
<asp:TextBox ID="cTextBox" runat="server" />
//script
var Members =
{
aTextBox: $("#<%=aTextBox.ClientID %>"),
bTextBox: $("#<%=bTextBox.ClientID %>"),
cTextBox: $("#<%=cTextBox.ClientID %>")
}
Try the Sessions...
Make a session in your class (I assume you have a General class)and use its reference to access it on any page you want. But remember you have to assign a value before using it.
e.g,
below is a session of UserID.
public static int UserId
{
get
{
if (HttpContext.Current.Session["UserId"] != null)
return Convert.ToInt32(HttpContext.Current.Session["UserId"]);
else
return 0;
}
set
{
HttpContext.Current.Session["UserId"] = value;
}
}
First you have to store value in your session as soon as you application starts.
User user = new user(); // consider you have a User class
protected void btnLogin_OnClick(object sender, EventArgs e)
{
_user.Username = this.txtUserName.Text;
_user.Password = this.txtPassword.Text;
if (_user.Validate())
{
General.UserID = _user.UserID; // here you are storing the id of logged in user
Response.Redirect("~/HomePage.aspx");
}
else
{
this.labelNotice.Text = "Invalid Username or Password";
}
}
To access the value of this session on any page in javascript,
<%# Import Namespace="MyProject.Models" %>
<script type="text/javascript">
var myID;
function GetMyID() {
myID= '<%=General.UserId%>';
}
</script>
I imported my General class which is placed in the Models folder in MyProject solution.
I am trying to populate a hidden field with the values that are added to my list box. I am getting the message _delimiter is not declared. So the hidden field value would be 123456,651456,654321 etc..
<script language="javascript" type="text/javascript">
function getSelected(source, eventArgs) {
var s = $get("<%=NameTextBox.ClientID %>").value;
var opt = document.createElement("option");
opt.text = s.substring(s.length - 10);
opt.value = s.substring(s.length - 10);
document.getElementById('<%= Listbox.ClientID %>').options.add(opt);
$hidlistbox = $('#<%= hidListBox.ClientID %>');
$textbox = $('#<%= NameTextBox.ClientID %>');
$hidlistbox.val($hidlistbox.val() + $textbox.val() + '<%= _delimiter %>');
$textbox.val('');
}
Private Sub PopulateListBox()
Dim _delimiter As Char = ","c
If NameTextBox.Text = "" Then
Else
' Get value from text box
Dim textBoxValue As String = Me.NameTextBox.Text
' Create new item to add to list box
Dim newItem As New ListItem(textBoxValue)
' Add item to list box and set selected index
Listbox.Items.Add(newItem)
Listbox.SelectedIndex = Listbox.Items.Count - 1
hidListBox.Value = _delimiter.ToString
End If
End Sub
In your javascript, you are trying to evaluate the server side _delimiter variable, which seems to be private to the PopulateListBox method.
You should either define a public _delimiter property in your code behind, or double check if you really need its evaluation in the javascript.