如果該位置尚未存儲,則可以使用操作篩選器檢查會話中的值並重定向到視圖。一旦被捕獲,您可以重定向回原始視圖。
是這樣的:任何需要的地方在一個控制器/動作
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();
}
}
這意味着該位置選擇視圖將呈現(冗餘)多次。如果有關聯的數據庫查詢(檢索位置列表),這也會增加開銷。 – MarkG
另外,可以應用操作過濾器來查看操作或控制器或全局。 – MarkG
視圖將有機會渲染很多次,是的。但是,它會檢查模型值,看它是否真的需要顯示選擇UI。此外,除非Session變量不存在,否則不會有數據庫命中。例如,檢查Session var,如果不存在,則敲入DB,存儲在Session中,返回模型。如果Session var存在,只需設置模型值並返回;沒有數據庫命中。 – ventaur