简体   繁体   English

在同一页面上呈现局部视图

[英]render partial view on same page

In my navigation bar, I have Search 在我的导航栏中,我有搜索

 <li><a href="#" class="callSearch">Search </a></li>

I am making Ajax call, to go to different projects controller 我正在打电话给Ajax,去其他项目的控制器

 $(".callSearch").click(function (e) {
    e.preventDefault();

    var url = '@Url.Action("Search", "Search")';
    $.ajax(
        {
            type: "GET",
            url: 'Search/Search',
            //dataType: "json",
            success: function () {
                window.location = "https://localhost:xxx/Search/Search";
            },
            error: function () {
                alert("Error");
            }
        });

});

Controller 控制者

  [HttpGet]
    public ActionResult Search()
    {
        return PartialView("~/Views/Search/_Search.cshtml");
    }

With this code I posted the partial view is opening in new page. 使用此代码,我发布了部分视图,它将在新页面中打开。 Search controller is in different project and layout file that has navigation and js is in different project. 搜索控制器位于不同的项目中,具有导航的布局文件,而js位于不同的项目中。

I want to return the modal on the same page ....But right now its going to different page and navigation is gone on that page. 我想在同一页面上返回模态....但是现在它转到不同的页面,导航在该页面上消失了。

Any ideas on how to do that? 关于如何做到这一点的任何想法? I tried using Render a partial view inside a Jquery modal popup on top of a parent view but didnt work for me. 我尝试在父视图顶部的Jquery模态弹出窗口中使用“ 渲染局部视图”,但对我没有用。

The window.location command causes your browser to navigate to a new location, as specified by the given URL. window.location命令使您的浏览器导航到由给定URL指定的新位置。

Instead choose some existing element on your page where you wish to inject the contents of the partial, and set the innerHTML property of that element to be the contents of the response. 而是在页面上选择要注入部分内容的现有元素,并将该元素的innerHTML属性设置为响应的内容。 eg let's say you have an existing div somewhere like this: 例如,假设您在这样的某个地方有一个现有的div:

<div id="results"></div>

Then, in your JavaScript you can do this: 然后,可以在JavaScript中执行以下操作:

$(".callSearch").click(function (e) {
    e.preventDefault();

    var url = '@Url.Action("Search", "Search")';
    $.ajax(
        {
            type: "GET",
            url: 'Search/Search',
            dataType: "html",
            success: function (response) {
                $("#results").html(response); //set the HTML content of the "results" div to be the response from the server, which contains the HTML generated by execution of the partial view
            },
            error: function () {
                alert("Error");
            }
        });
});

NB Note that if you are making an ajax call to another project at a different URL and/or port you may have to setup the other project to accept CORS requests. 注意注意,如果要通过其他URL和/或端口对另一个项目进行ajax调用,则可能必须设置另一个项目以接受CORS请求。

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

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