1

在我的ASP.net MVC 3(基于 nopcommerce 的)应用程序中,我需要确保用户从列表中选择他的位置,并且此选择存储在会话中以进行动态价格计算。因为,可能有多个入口点(主页、搜索结果、来自 Google 索引页面等)。我想确保在用户尝试查看任何产品时立即将位置选择(可能是弹出窗口)呈现给用户可能有价格的页面。对于给定的会话,这必须是一次性选择。

Application_BeginRequest执行检查特定会话变量是否存在的最佳事件处理程序 ( ??) 是什么?

4

3 回答 3

4

您可以使用操作过滤器检查会话中的值,如果该位置尚未存储,则重定向到视图。捕获后,您可以重定向回原始视图。

就像是:

public class CheckLocationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var location = filterContext.HttpContext.Session["Location"];

        if (string.IsNullOrWhiteSpace(location))
        {
            // store the requested URL for use once location has been chosen
            filterContext.Controller.TempData["ReturnToUrl"] = filterContext.HttpContext.Request.Url;

            // redirect to location choice view
            filterContext.Result = new RedirectResult(VirtualPathUtility.ToAbsolute("~/Location/Choose"));
        }
    }
}

然后在需要时在控制器/操作中使用此属性:

public class SomeController : Controller
{
    [CheckLocation]
    public ActionResult Index()
    {
        // location has been checked so continue

        return View();
    }
}
于 2012-12-31T06:39:36.870 回答
0

您可以使用操作过滤器来全局检查会话变量。但是,如果您想在某些页面上显示选择 UI 而无需重定向,您可能最好使用带有支持它的操作的局部视图(例如,Html.RenderAction())。

在您希望向用户展示此选择 UI 的任何视图中调用 RenderAction 助手。该操作将检查会话变量。根据会话变量是否存在,为操作设置一些模型值并部分设置为真/假。然后让局部视图检查该模型值并相应地显示选择 UI(即,如果值指示用户需要进行选择,则显示弹出窗口)。

于 2012-12-31T06:42:17.983 回答
0

在控制器的操作中,您可以检查:

if(HttpContext.Current.Session["Shown"] == null){
    HttpContext.Current.Session["Shown"] = true;
    // turn on a flag for client to know it should show popup
}
于 2012-12-31T06:49:56.070 回答