简体   繁体   English

使用Ajax C#在不同的Controller / Action中调用一个动作

[英]Call an action inside different Controller/Action using Ajax C#

I have _layout file what I want to show on different pages of my project 我有_layout文件,要在项目的不同页面上显示

_layout.cshtml _layout.cshtml

<html>
xxxxx
</html>

my _layout has a navigation bar I decided to create a partialView to be able to show that navigation bar using another controller different from my "home" controller 我的_layout有一个导航栏,我决定创建一个partialView ,以便能够使用不同于“ home”控制器的另一个控制器来显示该导航栏

NavegationController NavegationController

public class NavBarController : Controller
{
    // GET: NavBar
   [ChildActionOnly]
    public PartialViewResult BarraNavegacion()
    {
        return PartialView("~/Views/Shared/_navbar.cshtml");
    }

    [HttpPost]
    public string LogOut(string data)
    {
        FormsAuthentication.SignOut();
        return "bye";
    }
}

In my _layout I added the following line: 在我的_layout ,添加了以下行:

@{Html.RenderAction("BarraNavegacion", "NavBar");}

So far everything works, the navigation bar is displayed well 到目前为止一切正常,导航栏显示良好

My navbar has a log out button, so I tried to implement the LogOut method using ajax 我的导航栏有一个注销按钮,因此我尝试使用ajax实现LogOut方法

script Log out 脚本注销

//Boton salir
    $('.salirUsuario').click(function() {

        console.log("salio");

        $.ajax({
            url: 'LogOut',
            method: "POST",
            data: { data: "xx" },
            async: false,
            dataType: "json",
            success: function (json) {

                window.location.href = '@Url.Action("Login","Login")';
            }
        });

but received the following console error 但收到以下控制台错误

jquery-3.4.1.min.js:2 POST http://localhost:9887/Home/LogOut 404 (Not Found)

I know The application tries to find the method/Action " LogOut " in " Home " (which is the view where I am at the moment), but how do I go to NavBar / LogOut of the controller that I created called NavBar and not go to " Home "or any other view where I am at time? 我知道应用程序尝试在“ Home ”(这是我目前所在的视图)中找到方法/操作“ LogOut ”,但是如何转到我创建的名为NavBar的控制器的NavBar / LogOut而不是转到“ Home ”或我当时所在的任何其他视图?

You can add the following line if you want to include the navbar for few views like 如果要包括一些视图之类的导航栏,则可以添加以下行

@Html.Partial("~/Views/Controller/View.cshtml", model)

Suppose you want to use it in the master layout page, add the above in _layout.chtml and you can call the below codes for rendering the master layout 假设要在主版面页面中使用它,在_layout.chtml添加以上内容,然后可以调用以下代码来呈现主版面

@{
Layout = "~/Views/Shared/_layout.cshtml";
}

and for logout just do the following script 对于注销,只需执行以下脚本

 $('.salirUsuario').click(function() {
      window.location.href = '/NavBar/LogOut';          
 });

The LogOut action you are wanting to Post to is on your NavBarController , but in your current AJAX function the asp.net MVC framework will try to find the LogOut route on the default controller path, which is your "Home" controller because you are setting your AJAX URL property to url: 'LogOut' . 您要发布到的NavBarController位于NavBarController ,但是在当前的AJAX函数中,asp.net MVC框架将尝试在默认控制器路径(即“ Home”控制器)上查找LogOut路由,因为您正在设置您的AJAX URL属性以url: 'LogOut' You need to be more specific about the route location in your URL. 您需要更详细地说明URL中的路线位置。

For Razor page javascript: 对于Razor页面javascript:

Your AJAX Url needs to include your controller path, so you can do something like this if this javascript is in a razorpage (.cshtml) file: 您的AJAX网址需要包含您的控制器路径,因此,如果此javascript位于razorpage(.cshtml)文件中,则可以执行以下操作:

    $.ajax({
        url: '@Url.Content("~/NavBar/LogOut")',
        method: "POST",
        data: { data: "xx" },
        async: false,
        dataType: "json",
        success: function (json) {

            window.location.href = '@Url.Action("Login","Login")';
        }
    });

For referenced javascript file: 对于引用的javascript文件:

If your javascript code is in a separate javascript file that is referenced, then you can make a variable in your Layout page for your application's base URL path, and then you can use that variable in any included javascript file as long as you declare that variable in your layout page before adding any script tags to reference javascript files. 如果您的JavaScript代码在所引用的单独的javascript文件中,则可以在“布局”页面中为应用程序的基本URL路径创建一个变量,然后只要声明该变量,就可以在任何包含的javascript文件中使用该变量。在您的布局页面中添加任何script标记以引用javascript文件之前。

layout page file first script tag could be: 布局页面文件的第一个script标签可以是:

<script type="text/javascript">
    var baseApplicationPath = '@Url.Content("~/")';
</script>

then if your AJAX is in another referenced javascript file, you could do something like this wherever needed: 那么,如果您的AJAX位于另一个引用的javascript文件中,则可以在需要的地方执行以下操作:

    $.ajax({
        url: baseApplicationPath + 'NavBar/LogOut',
        method: "POST",
        data: { data: "xx" },
        async: false,
        dataType: "json",
        success: function (json) {
            window.location.href = baseApplicationPath + 'Login/Login';
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM