【问题标题】:MVC 3 How to tell what view a controller action is being called from-MVC 3 如何判断从哪个视图调用控制器操作-
【发布时间】:2012-12-27 22:45:17
【问题描述】:

有没有办法告诉控制器动作是从哪个视图调用的? 例如,我想使用“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 });
        }
    }

【问题讨论】:

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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    目前我正在使用类似的东西:

    在视图中,我使用以下方法填充 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 变量。

    【讨论】:

      【解决方案3】:

      我找到了另一种方法。 在控制器中,您想知道它是从哪个页面调用的。 我在控制器中添加了以下内容

      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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多