MVC 3如何判断正在调用控制器操作的视图 -

时间:2012-12-27 22:45:18

标签: asp.net-mvc-3 view controller

有没有办法告诉从哪个视图调用控制器操作? 例如,我想使用“ControllerContext.HttpContext.Request.PhysicalPath”,但它返回控制器操作本身所在的路径:

    public ActionResult HandleCreateCustomer()
    {
        // Set up the customer
        //..code here to setup the customer

        //Check to see of the calling view is the BillingShipping view
        if(ControllerContext.HttpContext.Request.PhysicalPath.Equals("~/Order/BillingShipping"))
        {
            //
            return RedirectToAction("OrderReview", "Order", new { id = customerId });
        }
        else
        {
            return RedirectToAction("Index", "Home", new { id = customerId });
        }
    }

3 个答案:

答案 0 :(得分:1)

如果您有可能从中调用的固定位置数,则可以创建一个枚举,其中每个值都对应于可以从中调用的位置。然后,您只需将此枚举值传递给HandleCreateCustomer,并根据该条件执行条件语句。

答案 1 :(得分:0)

目前我正在使用那种东西:

在View中我使用:

填充TempData变量
@{TempData["ViewPath"] = @Html.ViewVirtualPath()}

HtmlHelper方法ViewVirtualPath()在System.Web.Mvc.Html命名空间中找到(像往常一样),如下所示,返回表示View虚拟路径的字符串:

public static string ViewVirtualPath(this HtmlHelper htmlHelper)
    {            
        try{
            return ((System.Web.WebPages.WebPageBase)(htmlHelper.ViewDataContainer)).VirtualPath;
        }catch(Exception){
            return "";
        }
    }

然后我会明显地读取控制器中的TempData变量。

答案 2 :(得分:0)

我发现了另一种方式。 在控制器中,您想知道从哪个页面调用它。 我在控制器中添加了以下内容

ViewBag.ReturnUrl = Request.UrlReferrer.AbsolutePath;

然后在视图中我有一个'返回'按钮

@(Html.Kendo().Button().Name("ReturnButton")
            .Content("Back to List").Events(e => e.Click("onReturn"))
            .HtmlAttributes(new { type = "k-button" })
        )

然后是onReturn处理程序的javascript

function onReturn(e) {
    var url = '@(ViewBag.ReturnUrl)';
    window.location.href = url;
}