Using Response.Redirect within a Webmethod

I am facing an issue with the response.redirect command in my webmethod call. Here is a snippet of my code:

HTML:

<a onclick="proximaAula()">Next Lesson -></a>

JS:

 function proximaAula() {
    var tipo = getParameterByName('t');
    if (tipo == "1") {
        //PageMethods.MyMethod(projekktor('player_a').getPosition(), projekktor('player_a').getDuration(), getParameterByName('codaula'));
        PageMethods.NextAula(projekktor('player_a').getPosition(), projekktor('player_a').getDuration(), getParameterByName('codaula'));
    }
    //alert(tipo);
    if (tipo == "3") {
        var iframe = document.getElementById('viewer');
        var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
        var pag;
        var npag;
        if (iframeDocument) {
            elem = iframeDocument.getElementById('pageNumber').value;
            npag = iframeDocument.getElementById('numPages').innerHTML;
            npag = npag.substring(3, npag.length);
        }
        //return "asasdas"; // 
        //alert(elem + " - " + npag);
        PageMethods.NextAula(elem,npag,getParameterByName('codaula'));
    }
    if (tipo == "4") {
        PageMethods.NextAula("-1","-1",getParameterByName('codaula'));
    }
}

C#:

[WebMethod]
    public static string NextAula(string tempo, string tempomax, string codaula)
    {
        escolawebEntities DB = new escolawebEntities();
        string link = "";
        int icodaula = int.Parse(codaula);

        eadaulaaluno eaula = (from x in DB.eadaulaaluno where x.codeadaula == icodaula select x).FirstOrDefault();

        tempo = tempo.Substring(0, tempo.IndexOf('.'));
        tempomax = tempomax.Substring(0, tempomax.IndexOf('.'));

        int ntempo = ((int.Parse(tempo) * 100) / int.Parse(tempomax));

        if (tempo == tempomax || eaula.percentual == eaula.percentualmax || ntempo >= 95 )//ou perc ser maior 98%
        {
            eadaula aaula = (from x in DB.eadaula where x.eadcodaula == icodaula select x).FirstOrDefault();
            eadaula paula = (from x in DB.eadaula 
                             where x.eadcodcursomodulo == aaula.eadcodcursomodulo
                             where x.ordem == aaula.ordem + 1
                             select x).FirstOrDefault();

            if (paula != null)
            {
                //link = "eadVerAula.aspx?codaula=" + paula.eadcodaula + "&t=" + paula.eadcodmidia;
                HttpContext.Current.Response.Redirect("eadVerAula.aspx?codaula=" + paula.eadcodaula + "&t=" + paula.eadcodmidia,false);
                //Context.Response.StatusCode = 307;
                //Context.Response.AddHeader("Location", "<redirect URL>");

               // HttpContext.Current.Response.StatusCode = 307;

               // HttpContext.Current.Response.AddHeader("Location", "eadVerAula.aspx?codaula=" + paula.eadcodaula + "&t=" + paula.eadcodmidia);
            }
                //HttpContext.Current.Response.Redirect("eadVerAula.aspx?codaula=" + paula.eadcodaula + "&t=" + paula.eadcodmidia);
                //link = "eadVerAula.aspx?codaula=" + paula.eadcodaula + "&t=" + paula.eadcodmidia;
        }
        return "";
    }

I have tried different methods to redirect the page but faced challenges. This code functionality involves clicking a link that triggers a JavaScript function to send information to the server using a webmethod.

Answer №1

When calling an asynchronous method or redirecting based on website values, you can utilize this code line for redirecting the website:

document.location.href = url;

Instead of implementing redirects in your server-side code, simply pass the link directly from [WebMethod] -NextAula and handle it on the JavaScript side.

To retrieve the value, use

"eadVerAula.aspx?codaula=" + paula.eadcodaula + "&t=" + paula.eadcodmidia"
.

Answer №2

Redirecting a website to another address cannot be achieved using Response.Redirect in a webmethod. Instead, the webmethod will return an XML response to the caller. To redirect your page, send the necessary information from the webmethod and use it accordingly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding a close button to an iframe in Angular: A step-by-step guide

I am struggling with an iframe that pops up when a button is clicked. However, the only way to close or collapse it is by clicking outside the window. I would like to have a close button in the top left corner of the popup so that users can easily close th ...

What is the best way to display hover-over text pop ups on menu list items in jsTreeR?

As a dedicated user of the jsTreeR package within Shiny, I have been exploring the functionality it offers. By executing the code below, users are presented with a draggable menu at the top, allowing them to drag items down to the designated list labeled " ...

Can someone help me understand why my component is not rendering when placed inside a conditional block, but it renders fine on its own?

I want to display a specific page only if the user is currently logged in; otherwise, prompt them to log in. My approach involves leveraging Firebase authentication for this functionality. import Head from "next/head"; import { auth } from "../../comp ...

Using javascript-time-ago in combination with react and redux: A comprehensive guide

Hey there! I'm currently working on a simple todo application using Reactjs and Redux. Within each todo, I have two properties: todo name and time. All my todos are stored in Redux. The challenge I'm facing is that when a user fetches todos, I wa ...

Choosing a value does not automatically activate the SelectedIndexChanged event

My current situation involves the need for the SelectedIndexChanged event to be triggered when an item is selected programmatically. Here is my approach: On FormLoad, I populate a dropdownlist with data from the database and set the value of the drop down ...

Interaction with three.js objects by clicking

I am looking for a way to show or hide objects by simply clicking a button. For example, when the button is clicked on the GUI, obj1 should be hidden and obj2 revealed. I tried using object.traverse(object.visible=false); but it doesn't seem to be ...

Can different scripts be used to call a single script?

I'm trying to display random images in four divs using code I found on SO: <script type="text/javascript> function get_image(div_id){ var imgCount = 3; var dir = 'images/'; var randomCount = ...

React-router: Issue with ProtectedRoute authentication mechanism not functioning as expected

I'm currently working on setting up protected routes that can only be accessed after the user has logged in. There are two main routes to consider: /login, which is the Login component (public), and /, which is the Dashboard component (protected). Wh ...

What is the best way to identify which JavaScript code is triggering or managing an event?

In the development of an HTML5 application framework designed for businesses to use on their intranet and extranet sites, a SAP JEE application server is utilized. The framework incorporates the grid system known as "Semantic UI" along with various JavaScr ...

Styling a nested scrollbar using JQuery

I am looking to customize two scrollbars using a jquery plugin or JS library. Here is the HTML code: <div id="container"> <div class="fixedHeightContainer"> <div class="fixedHeightContent"> Lorem ipsum dolor sit amet, con ...

What is the best way to access the value chosen in a TextBox using a JavaScript Function in C# code-behind?

aspx.cs: <script type="text/javascript"> $(function () { //ALPHA $('#COLOR_ALPHA_TEXTBOX1').colorPicker({ pickerDefault: "E1E1E1", colors: ["E1E1E1", "33CC00", "FFF000", "CC0000", "996600", "FF9900", "303030", "0066FF", ...

An issue has been encountered in the following module federation: `TypeError: g.useSyncExternalStore is not a function`

I encountered an error after deploying my next app with module federation: TypeError: g.useSyncExternalStore is not a function The same app works fine as a standalone application when run with yarn dev or yarn start, but it fails when using module federat ...

Learn how to prevent a button from being clicked until a different button is activated using jQuery

I'm currently working on implementing jQuery code to prevent users from clicking the registration button unless they have clicked on the survey button first, which triggers a modal window. Can anyone offer some assistance with this? The main requirem ...

The useAutocomplete function in Material-UI fails to consider the disabled

Currently, I am working on developing my own Autocomplete component by utilizing the useAutocomplete hook from the mui/base package. Most parts of the implementation are functioning correctly, except for the disabled option. My expectation is that the com ...

Encountering issues with Node-persist on a complex Node.js application leading to missing return

I've encountered an issue with my heavy node app where I'm using node-persist to save data locally. Specifically, in a certain step of the process, I have the following code: const localdb = require('node-persist') const storage = loca ...

How do I use jQuery to make a div appear when the previous one closes?

I've been experimenting with some code and it's gotten pretty lengthy. It works fine with just a few divs, but what if I need to implement this on 20 or more...? Is there a way to condense the code I've written? (I'm still new to jque ...

Is there a way to run a test multiple times until it fails after a certain number of repeats have been reached?

Currently, our team is in the process of creating selenium tests using C# and Visual Studio's test runner. We have set up schedules to run these tests using vstest.console.exe. One recurring issue we are facing is that sometimes tests fail even though ...

Having trouble retrieving the full png image using PhantomJs render command

Currently, I am utilizing PhantomJS to convert an html file into a png image. However, the html file is quite long horizontally and when using PhantomJs to render it as an image, it does not capture the entire length up to the last horizontal scroll. I a ...

Is there a way to adjust the pivot point of a cone scale in three.js?

I am trying to resize a cone that is generated using THREE.CylinderGeometry. My goal is to make it longer and have it grow in the direction of the negative z-axis, but I've noticed that currently it's growing in both negative and positive directi ...

Uncovering the secrets of extracting form parameters with jquery.ajax in asp.net

In search of a method to extract form parameters in C# similar to Java's request.getParameter("blah"). I am currently serializing my form with jQuery and sending it to a web method, but I need assistance in extracting the data. Using ajax. $("#btn" ...