calling an actionresult of a controller in javascript

Well, to help my fellow beginners. This is the solution I coped up.

First of all, I learned that each ActionResult should have a View (If I am not mistaken).

So, In my AdminView.cshtml, I create a hidden button.

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

After that, In my JSFILE

I removed the ajax. which is in the first place is wrong.

   $("#logout").click(function () {
        swal({
            title: "ログアウト?",
            text: "アカウントからサインアウトしますか?",
            icon: "warning",
            buttons: true,
            dangerMode: true,
        })
            .then((willLogout) => {
                if (willLogout) {
                    $("#submitLogout").click();
                }
            });
    });

This function in javascript is to trigger the hidden button in .cshtml and trigger the ActionResult in the Controller.

Also, In my Controller. This is what I said that each ActionResult has to have a 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 is the name of the button which you want to trigger. If the trigger is successful, it will pass the value of the button to the argument string button.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top