Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 注销不会返回到正确的视图_C#_Jquery_Asp.net Mvc_Razor - Fatal编程技术网

C# 注销不会返回到正确的视图

C# 注销不会返回到正确的视图,c#,jquery,asp.net-mvc,razor,C#,Jquery,Asp.net Mvc,Razor,在我的布局页面中,我使用Request.IsAuthenticated方法显示登录和注销链接。登录链接弹出模式和登录表单。(模式弹出在部分页面中) 成功登录后,将显示注销链接。当我点击logout l时,它会转到logoff方法并重定向到Index操作,但它不会转到视图,而是显示相同的视图。 请帮我翻译一下。我花了很多时间来修复这个 版面页 <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">

在我的布局页面中,我使用Request.IsAuthenticated方法显示登录和注销链接。登录链接弹出模式和登录表单。(模式弹出在部分页面中)

成功登录后,将显示注销链接。当我点击logout l时,它会转到logoff方法并重定向到Index操作,但它不会转到视图,而是显示相同的视图。 请帮我翻译一下。我花了很多时间来修复这个

版面页

<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>

            </div>
            <div id="navbar" class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li class="active"><a href="#">Home</a></li>
                    <li><a href="#">About</a></li>

                    <li><a href="#">Contact</a></li>
                </ul>
                <ul class="nav navbar-nav navbar-right">
                    <li>
                        @if (Request.IsAuthenticated)
                        {
                            <div>
                                   Loggen As: @User.Identity.Name
                                </div>
                            <a id="logOut" style="cursor:pointer">
                                <span class="glyphicon glyphicon-log-out"></span> Logout
                            </a>
                        }

                        else
                        {
                            <div>
                                Loggen As: @User.Identity.Name
                                </div>
                                <a style="cursor:pointer" data-toggle="modal" data-target="#loginModal">
                                    <span class="glyphicon glyphicon-log-in"></span> Login
                                </a><h3>dsdasdasddsad</h3>
                                }


</li>
                </ul>
            </div>
        </div>
    </nav>

    <div id="loginModal" class="modal fade" data-backdrop="static" data-keyboard="false" role="dialog">
        <div class="modal-dialog">

            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Login</h4>
                </div>
                <div class="modal-body">

                    @Html.Partial("_LoginModal")

                </div>

                <div class="modal-footer">
                    <button id="Login" type="button" class="btn btn-success">Login</button>
                    <button type="button" class="btn btn-success" data-dismiss="modal">Close</button>
                </div>


            </div>

        </div>
    </div>

    <section id="main">
        @RenderBody()
        <p>Copyright W3schools 2012. All Rights Reserved.</p>
    </section>

    <script type="text/javascript">

        $('#logOut').click(function () {

            $.post("@Url.Action("Logoff", "Home")", function (data) {


            });

        });

        $('#Login').click(function (evt) {
            evt.preventDefault();
            var _this = $(this);
            var _form = _this.closest("form");
            var validator = $("form").validate();
            var anyError = false;

            $('#LoginForm').find("input").each(function () {
                if (!validator.element(this)) {
                    anyError = true;
                }
            });
            if (anyError)
                return false;
            var form = $('#LoginForm').serialize();
            $.ajax({
                type: "POST",
                url: '/Home/Index',
                data: form,
                dataType: "json",
                success: function (response) {

                    if (response.isRedirect && response.isUser) {
                        // alert('1');
                        window.location.href = response.redirectUrl;
                    }
                    else if (response.isRedirect && response.isAdmin) {
                        // alert('2');
                        window.location.href = response.redirectUrl;
                    }

                    else if (!response.isRedirect) {
                        $('#LoginForm').find("#message").text(response.errorMessage);


                    }

                },
                error: function (response) {
                    alert("Some error");
                }

            });



        });
    </script>

我进行ajax调用,ajax调用保持在同一页面上。因此,我将ajax调用替换为适合我的操作链接


感谢Stephen Muecke的快速正确回答

进行ajax调用时,ajax调用保持在同一页面上。如果您想转到另一个页面,那么不要使用ajax。是的,这很有意义:)。替代方案是什么。实际上,每当我单击注销时,它都会转到注销方法,并重定向到索引页,但最后它将返回相同的视图/admin/index,只要有一个指向
logoff()
的链接,该链接将重定向回
/Home/index
哇。Stephen Muecke你发现问题的速度有多快。谢谢。我怎么没有意识到我正在使用ajax post。这就是我喜欢编码的方式。。。。。
@model WebApplication6.ViewModel.LoginViewModal
@using WebApplication6.ViewModel

<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @id = "LoginForm", @class = "form-horizontal" }))
{
    @Html.ValidationSummary(true, "Login failed. Check Login details")
    <div class="form-group">
        @Html.LabelFor(m => m.UserName, new { @class = "col-sm-3 control-label" })
        <div class="col-sm-9">
            @Html.TextBoxFor(x => x.UserName, new { @class = "form-control", @placeholder = "Enter UserName" })
            @Html.ValidationMessageFor(x => x.UserName)
        </div>
    </div>


                        <div class="form-group">
                            @Html.LabelFor(m => m.Password, new { @class = "col-sm-3 control-label" })
                            <div class="col-sm-9">
                                @Html.PasswordFor(x => x.Password, new { @class = "form-control", @placeholder = "Enter UserName" })
                                @Html.ValidationMessageFor(x => x.Password)
                            </div>
                        </div>

                        <div class="form-group">
                            @Html.Label("User Type", new { @class = "col-sm-3 control-label" })
                            <div class="col-sm-3">
                                @Html.DropDownList("userType",
           new SelectList(Enum.GetValues(typeof(UserType))), new { @class = "form-control" })
                            </div>
                        </div>

                        <div class="form-group">

                            <div id="message"  style="color:#ff0000; font-weight:bold;" class="col-sm-offset-3 col-sm-12">

                            </div>

                        </div>


}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WebApplication4.Helper;
using WebApplication6.Models;
using WebApplication6.ViewModel;

namespace WebApplication6.Controllers
{
    public class HomeController : Controller
    {


        // GET: Home
        public ActionResult Index()
        {
            return View();
        }




        [HttpPost]
        public JsonResult Index(LoginViewModal lm)
        {
            CareManagementEntities db = new CareManagementEntities();
            if (ModelState.IsValid)
            {
                var userActive = db.Usrs.Where(x => x.Usr_Nm == lm.UserName && x.IsActive == true && x.IsDeleted == false).FirstOrDefault();
                if (userActive != null)
                {
                    var userss = db.Usrs.Where(x => x.Usr_Nm.ToLower() == lm.UserName.ToLower()).FirstOrDefault();
                    var validPassword = PasswordHelper.ValidatePassword(lm.Password, userss.Usr_Pwd);
                    if (validPassword)
                    {
                        var users = db.Usrs.Where(x => x.Usr_Nm == lm.UserName).FirstOrDefault();
                        if (users != null)
                        {
                            var userWithRole = db.Usrs.Where(x => x.Usr_Nm == lm.UserName && x.Usr_Role == lm.userType.ToString()).FirstOrDefault();
                            if (userWithRole != null)
                            {
                                if (userWithRole.Usr_Role == "Admin")
                                {
                                    FormsAuthentication.SetAuthCookie(lm.UserName, false);
                                    return Json(new
                                    {

                                        redirectUrl = "/Admin/Index",
                                        isRedirect = true,
                                        isAdmin = true,
                                    });
                                }

                                else if (userWithRole.Usr_Role == "User")
                                {
                                    return Json(new
                                    {
                                        redirectUrl = "/UserPage/Index",
                                        isRedirect = true,
                                        isUser = true,
                                    });
                                }
                                else
                                {
                                    return Json(new
                                    {
                                        isRedirect = false,
                                        errorMessage = "The user name or password provided is incorrect."
                                    });

                                }

                            }

                            else
                            {
                                return Json(new
                                {
                                    isRedirect = false,
                                    errorMessage = "The user name or password provided is incorrect."
                                });
                            }
                        }

                    }

                    else
                    {
                        return Json(new
                        {
                            isRedirect = false,
                            errorMessage = "The user name or password provided is incorrect."
                        });

                    }


                }
                else
                {
                    return Json(new
                    {
                        isRedirect = false,
                        errorMessage = "The user name or password provided is incorrect."
                    });

                }
            }

            return Json(new
            {
                isRedirect = false,
                errorMessage = "Error happen please reload the page"
            });


        }


        public ActionResult Logoff()
        {
            FormsAuthentication.SignOut();
            Session.Abandon();

            // clear authentication cookie
            HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
            cookie1.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie1);

            // clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
            HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
            cookie2.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie2);

            FormsAuthentication.RedirectToLoginPage();
            return RedirectToAction("Index", "Home");
        }

    }
}