0

I have server-side VB code to retrieve an access_token and save it in the session. I want to make the token available client-side so I can use it to send an ajax request.

I tried to set the token in a hidden field. This works. The token shows in the field when I check via the browser dev tools.

I then tried to get the hidden field value in javascript with getHiddenValue(). This does not work. getHiddenVaue() does not execute. But when funciones.RedirigiraUsuario() is commented out, getHiddenValues() works.

RedirigiraUsuario() has a switch case to redirect a view depending on the profile

The vb code to set the token looks like this:

Dim url As String = funciones.getPropiedad(Me.Page, "urlWebApi") & 
"recuperarToken"
Dim data As New NameValueCollection()
data.Set("grant_type", "password")
data.Set("username", funciones.reemplaza_caracteres(txt_login.Text))

If ViewState("ESADMIN") Then
    data.Set("password", NegUsuario.get_GEN_claveUsuarios())
Else
    data.Set("password", contraseña)
End If

data.Set("clientid", "2")
'data.Set("idperfil", "63")
Dim sJson As String = funciones.ObtenerJsonWebApi(url, data)

If Not sJson = Nothing Then
    Dim json As Dictionary(Of String, String) = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(sJson)
    Session("TOKEN") = "Bearer " + json("access_token")
    'setting the token in hidden field
    inputToken.Value = "Bearer " + json("access_token")
    'here is the problem, this does not works, maybe the postback is the guilty
    ScriptManager.RegisterStartupScript(Me, Me.GetType(), "ShowStatus", "javascript: getHiddenValue();", True)
End If

funciones.RedirigiraUsuario(Me)

Javascript code :

<script type="text/javascript">

    $(document).ready(function () {
        $('#div_login').hide();
        $('#div_login').fadeIn(1500);
        document.getElementById('div_login').scrollIntoView();
    });

    function incorrecto() {
        $("#div_login").addClass('go');
    }

    function getHiddenValue() {
        console.error("asdasdasdasda")
        let hdnField = document.getElementById('<%= inputToken.ClientID %>').value;
        showNotificacion("asdas",'info', 'center', 'top',200)
        localStorage.setItem("PabToken", hdnField)
        sessionStorage.setItem("PabToken", hdnField)
        return true
    }

</script>

How can I execute the getHiddenValue() function before postback, or get the token saved in the server-side?

Edit

Public Shared Sub RedirigiraUsuario(ByRef pagina As Page)
    Select Case pagina.Session("PERFIL")
        Case "1", "2", "3", "4", "5", "N"
            pagina.Response.Redirect("~/Default.aspx")
        Case "6"
            pagina.Response.Redirect("~/FormMantenedor/MAN_JefeEspecialidad.aspx")
        Case "7"
            pagina.Response.Redirect("~/BUS_General.aspx")
        Case "8"
            pagina.Response.Redirect("~/FormPabellon/GST_Detalle_Post_Anestesia.aspx")
        Case "9"
            pagina.Response.Redirect("~/FormTabla/ING_Tabla.aspx")
        Case "10", "11", "12", "15"
            pagina.Response.Redirect("~/FormPreTabla/GST_Pre_Tabla.aspx")
        Case "14"
            pagina.Response.Redirect("~/GST_Camas.aspx")
        Case "13"
            pagina.Response.Redirect("~/FormPabellon/REP_Pabellon.aspx")
    End Select

End Sub
1
  • 1
    If the client ID is being troublesome, then you can add the attribute ClientIDMode = "static" to the inputToken control, then it will use the ID without changing it, so you could use let hdnField = document.getElementById('yourChosenID').value; instead. Control.ClientIDMode Property Commented Jan 21, 2023 at 20:18

1 Answer 1

1

I'm not sure. I need to repeat this: I'm not sure.

But my best guess is the problem is this line:

document.getElementById('<%= inputToken.ClientID %>')

What I think is happening is if funciones.RedirigiraUsuario(Me) results in a redirect, the <%= inputToken.ClientID %> expression will not resolve correctly.

To fix this, you need to set the clientID somewhere the javascript will be able to retrieve it before doing anything might cause a redirect.

The other potential issue is the reliance on ScriptManager.RegisterStartupScript(). It's possible a redirect will have the effect of resetting the script manager.

I think it's likely both issues are in play.

At very least you should be able to use the browser dev tools to find the function: does it have the correct clientID? Is it there at all?

Unfortunately, it's been far too long since I used Web Forms regularly. My recollection of how that all fits together is no longer clear, so this is as much help as I can give.

Sign up to request clarification or add additional context in comments.

6 Comments

thanksl for answer, i will add the funciones.RedirigiraUsuario(Me)
when funciones.RedirigiraUsuario(Me) is commented, it works. Redirecting is the problem. i tried use a "delay" 3 seconds but it does not work
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "ShowStatus", "javascript: getHiddenValue();", True) is ignored when i use a redirect. btw thanks for your answer
Remember: while your VB code is still running, the page in the browser doesn't exist, and it will not exist until the VB code for the entire page lifecycle is completely finished. If you redirect to a new page, all the work building up the previous page is thrown away.
thanks, i solved. i dont know if it is the best way to solve but it works. in the page load function on master page, i checked if the session has a "token", if token exist save the token in the local storage with javascript.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.