ASP.NET MVC当前请求url(ajax调用问题)

时间:2014-02-03 21:53:33

标签: asp.net ajax asp.net-mvc

我使用流行的技术“ReturnUrl”。我将当前页面的URL传递给服务器,做一些工作人员,然后我将用户重定向回此URL。例如,用户发表评论,然后返回此网址。

@using (Html.BeginForm("AddUserComment", "Home", new { returnUrl = HttpContext.Current.Request.RawUrl }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
}

但是,当我通过ajax调用加载此表单时,如下所示:

$.ajax({
        type: 'GET',
        url: '/Home/ShowUserCommentsBlock/',
        data: { entityType: entityType, entityId: entityId },
        cache: false,
        ...
    });

HttpContext.Current.Request.RawUrl返回ajax请求网址"/Home/ShowUserCommentsBlock?entityType=...",但我需要当前页面网址,其中调用了ajax请求。 我应该使用什么而不是HttpContext对象?

3 个答案:

答案 0 :(得分:4)

好的,我知道了。我们可以使用Request.UrlReferrer属性为ajax请求检索正确的URL,如下所示:

public ActionResult MyActionMethod()
{
            if (Request.IsAjaxRequest())
                ViewBag.ReturnUrl = HttpContext.Request.UrlReferrer.LocalPath;
            else
                ViewBag.ReturnUrl = HttpContext.Request.RawUrl;

            return View();
}

答案 1 :(得分:3)

您可以将当前页面网址作为AJAX请求中的某个属性传递。

以这种方式说出你的AJAX请求 -

        $.ajax({
            url: "@Url.Action("Submit")",
            type: "POST",
            data: {
                Url: '@HttpContext.Current.Request.Url'
            , entitytype: 'this is type'
            },
            error: function (response) {
                if (!response.Success)
                    alert("Server error.");
            },
            success: function (response) {
                alert(response);
            }
        });

然后在名为Url的POST操作中再添加一个参数。你会得到你在那里传递ajax请求的网址。

enter image description here

将Url放入Viewbag,然后将其分配给ReturnUrl。

ViewBag.Url = Url;

分配如下 -

@using (Html.BeginForm("Comments", "Ajax", new { returnUrl = ViewBag.Url}, FormMethod.Post, new { enctype = "multipart/form-data" }))
{

}

答案 2 :(得分:1)

您需要使用ajax请求发送页面的url(借助javascript代码中的一些razor)然后在控制器中将其存储在Viewbag中,然后使用它代替HttpContext.Current.Request.RawUrl < / p>