如何在使用ajax调用后返回视图

时间:2018-02-05 11:24:09

标签: ajax asp.net-ajax

我正在尝试在ajax调用后加载视图。在ajax调用之后,我的action方法将返回一个视图,该视图将在调用成功后加载。 问题是该视图根本没有出现,请帮助

控制器

 [HttpPost] public ActionResult Details(Guid id)
    {   

           return PartialView("Details",r.GetKupacById(id));
    }

的Ajax

         $.ajax({    type: "POST",
                url: '@Url.Action(controllerName:"Home",actionName:"Details")',
                data: { "id": $(".IDKupac")[ind].value },

                success: function (data) {

                    alert('Succes!');

                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            })

查看

   @model Kupac
   @{
    ViewBag.title= "Details"; 

    List<Kupac> lista = ViewBag.kupci as List<Kupac>;
    }

 <table cellpadding="0" cellspacing="0" border="0">
<tr>
    <td valign="top"><b>@Html.DisplayNameFor(model => model.Ime):</b></td>
    <td>
        @Html.DisplayFor(model => model.Prezime)
        <br />
        @Html.DisplayFor(model => model.OIB),

        <br />

    </td>
</tr>

1 个答案:

答案 0 :(得分:0)

好吧,让我们明确一点: AJAX 制作 HTTP请求。如果您发出 POST 请求,则会查找 响应数据 ,而不是 页面

页面是HTML和CSS,而数据是您在控制器中运行的计算过程的结果。

现在找到解决方案:我知道您需要在成功后重定向到新页面。有一个JavaScript功能:

window.location = 'https://google.com';

以上代码将网页重定向到Google网站。在你的成功回调中使用它:

 $.ajax({    type: "POST",
            url: '@Url.Action(controllerName:"Home",actionName:"Details")',
            data: { "id": $(".IDKupac")[ind].value },

            success: function (data) {

                window.location= 'someURLOfNewPage';

            },
            failure: function (response) {
                alert(response.responseText);
            },
            error: function (response) {
                alert(response.responseText);
            }
        })

它会重定向你。

记住:AJAX返回身体数据。即使您在响应中发送了一个页面, 也会将其视为数据 。不是 页面

一切顺利。