Invoking a Controller's ActionResult with Javascript

I'm attempting to invoke an ActionResult from a Controller in JavaScript.

The ActionResult is located in my AdminController.

[HttpPost]
public ActionResult Logout()
{
    return RedirectToAction("Login", "Login");
}

This is the Logout button in AdminView.

<a class="navbar-link" id="logout" name="logout" href="#">
    ログアウト
</a>

Now, I am trying to create an event in JavaScript.

  $("#logout").click(function () {
        swal({
            title: "ログアウト?",
            text: "アカウントからサインアウトしますか?",
            icon: "warning",
            buttons: true,
            dangerMode: true,
        })
            .then((willLogout) => {
                if (willLogout) {
                    //swal("Poof! Your imaginary file has been deleted!", {
                    //    icon: "success",
                    //});
                    $.ajax({
                        url: "/Admin/Logout",
                        type: 'POST',
                        success: function (result) {
                            document.location.reload(true);
                        }, 
                        error: function (result) {

                        }
                    });
                }
            });
    });

The main objective here is to redirect the user to the Login Page using the Controller.

I tried placing the swal("Poof")... inside the .then(willLogout) and it worked fine.

However, when I attempt to call the ActionResult using ajax, it doesn't work as expected.

Upon checking the console, it appears that nothing is being displayed.

I'm unsure of what mistake I might be making.

How can I effectively call the ActionResult from Controller to the JavaScript file using an Ajax call?

Answer №1

For the benefit of newbies like myself, I wanted to share the solution that worked for me.

I quickly realized that each ActionResult needed a corresponding View.

So, within my AdminView.cshtml, I added a hidden button.

<button type="submit" id="submitLogout" name="button" value="logout" hidden>logout</button>

Next, in my JSFILE

I removed the erroneous ajax call.

$("#logout").click(function () {
    swal({
        title: "Logout?",
        text: "Do you want to sign out of your account?",
        icon: "warning",
        buttons: true,
        dangerMode: true,
    })
    .then((willLogout) => {
        if (willLogout) {
            $("#submitLogout").click();
        }
    });
});

This JavaScript function triggers the hidden button in .cshtml and activates the ActionResult in the Controller.

In my Controller, I made sure that every ActionResult had an associated View.

public ActionResult AdminView(string button)
{
    if (button == "logout")
    {
        FormsAuthentication.SignOut();
        Session.RemoveAll();
        Session.Abandon();
        return RedirectToActionPermanent("Login", "Login");
    }
    else
    {
        if (!(Session["UserInfo"] is UserModel))
        {
            return RedirectToActionPermanent("Login", "Login");
        }
        else
        {
            return View();
        }
    }
}

The parameter string button in the ActionResult represents the button's name that triggered the action. If the trigger is successful, the button's value is passed to the argument string button.

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

Merge Various Ng-Loops

I am working with an HTML structure in which each child has varying lengths: <div ng-repeat='element in treeView'> <div ng-repeat='element1 in element.children'> <div ng-repeat='element2 in element1.chil ...

I am facing an issue with effectively passing properties from a parent state to its child component

In the Login component, I set the authentication state using the token as false initially. After a successful login, the token is changed to true. function Login() { const [user, setUser] = useState({ name: '', email: '' }); const [ ...

Include a new key and its corresponding value to an already existing key within FormData

I have a form that includes fields for title, name, and description. My goal is to submit the form values using an API. To achieve this, I am utilizing jQuery to add key-value pairs to the FormData variable: formdata.append('description_text', jq ...

The function GetURLParameter(sParam) is displaying %20 as blank space in the webpage

I am facing an issue with a code that pulls URL parameters into the landing page. The problem is that it is including white spaces as %20. For example, if my URL parameter is: example.com/?title=my website, it would display my%20website on the page inste ...

A helpful guide on including an image file from a form in a jQuery ajax request

I've been working on a jQuery file upload helper and I'm trying to figure out how to append the File from the form or the entire Form data to the request. In the past, I've used ASP.NET code to handle images from the Request, but when I try ...

Exploring the method of implementing a "template" with Vue 3 HeadlessUI TransitionRoot

I'm currently working on setting up a slot machine-style animation using Vue 3, TailwindCSS, and HeadlessUI. At the moment, I have a simple green square that slides in from the top and out from the bottom based on cycles within a for-loop triggered by ...

Node.js/Express - unable to retrieve client body data on server

I am able to retrieve data from express but I am facing issues when trying to post data to express... client: <html> <button onclick="myFunction()">send</button> <script> const data = {"experience" : 0}; ...

Uncovering the deepest levels of nested arrays and objects in JavaScript without any fancy libraries - a step-by-step guide!

I have been struggling to find a solution to a seemingly simple problem. Despite searching through various sites and resources, I have not been able to figure out how to iterate over the innermost levels of a doubly nested data structure. I have tried usin ...

Having issues debugging in the browser as React seems to be undefined

I am trying to implement a Context system to store the login user's name and use it for protected routes. context.js import React from 'react'; const axios = require('axios'); export const AuthContext = React.createContext(null); ...

switch out asterisk on innerhtml using javascript

Is there a way to replace the asterisks with a blank ("") in the innerHTML using JavaScript? I've attempted this method: document.getElementById("lab").innerHTML = document.getElementById("lab").innerHTML.replace(/&#42;/g, ''); I also ...

Learning how to extract data from a JSON file using JavaScript

One of the challenges I'm facing involves a JSON file that looks like this: { "residents": [ { "name" : "Jacob", "title" : "King", "gender" : "Male", }, { "name" : "Luthor", ...

Steps on removing a file type from a Material UI textfield

I've been struggling to figure out how to clear a Material UI textfield with type="file" even after trying multiple approaches. My issue arises when I set a file size limit and display an error message if a user tries to upload a file larg ...

How to customize XMLHttpRequest in Firefox's WebExtension

Recently, I've been attempting to override the XMLHttpRequest.protype.open method within Firefox's WebExtension environment. My current approach involves the following code snippet written in a content script: var oldOpen = XMLHttpRequest.protot ...

What is the best way to extract multiple return values from the $.post function in jQuery?

How can I separate two variables retrieved from the server using the $.post method? Currently, when I attempt this, I receive a combined mixed value. Below is the code snippet: $(".spot_me").click(function() { var idea = $(this).attr("id"); ...

"Has the implementation of functions within the Serial API, specifically navigator.serial and SerialPort, not been completed

I’ve been attempting to establish a connection with the serial port through a web page, and it seems that the supported method for this is using the Serial API. var Serial = {}; (function() { 'use strict'; /* * Initiate the Serial ob ...

What is the best way to incorporate JavaScript code using Django tags in a Django template?

Situation: In my Django 1.9 project, I have a JavaScript loop that fetches JavaScript code stored in the database. This JavaScript includes some Django tags that I need to load when the script is inserted into my template. Here is the function: {% extends ...

Authentication with PassportJS using Google OAuth2 strategy

When using the PassportJS Google OAuth Strategy, I encountered an issue where the user id I serialize and send to the cookie for the browser does not return when attempting to deserialize it. This becomes evident when I use console.log on the user, which r ...

Saving information on localStorage is not possible

Recently, I created a demo for a basic Login and Logout application that utilizes an access token. If a user attempts to access another page without logging in (meaning the access token is null), they are redirected back to the Login page. Initially, I use ...

Updating corresponding key values in two JavaScript objectsORModify matched key values

I am in need to compare two objects and update the values of the first object with the updated values from the second object. For example: $scope.obj1={"id" : 1, "name" : "java"} $scope.obj2={"id" : 1, "name" : "java4you", "gender" : "male"} compare(des ...

How to center scroll overflowed div vertically on element using Angular (5)

I have created a unique table layout using divs and the flex property with Angular. Here is an example of how it looks: <div class="tbody"> <div class="tr" *ngFor="let ask of asks"> <div class="td centered red">{{ask.price | ...