2013-04-11 66 views
1

我有我的Global.asax設置具有以下在session_start:如何使用會話變量來確定視圖?

protected void Session_Start() 
{ 
    HttpContext.Current.Session.Add("sourceCode", "default"); 
} 

在我的控制器,我有以下幾點:

public ActionResult Index(string sourceCode) 
{ 
    if (sourceCode != null && sourceCode != "default") 
    { 
     Session["sourceCode"] = sourceCode; 
     return View(); 
    } 
    else 
    { 
     return View(); 
    } 
} 

我想根據本屆會議上能夠顯示不同部分的佈局變量。什麼是正確的方法來做到這一點?我可以從控制器加載部分視圖還是需要在視圖上處理這些視圖?

這是一個我希望使用網站範圍來確定特殊定價和着陸頁廣告素材的變量。我是否必須在每一個控制器上設置相同的結構,還是有更全球的方式來做到這一點?

感謝, 布賴恩

回答

0

通過MVC的慣例,控制器必須決定哪些瀏覽它應該打開。對於這個控制器中你有這樣的代碼:

public ActionResult Index(string sourceCode) 
{ 
if (sourceCode != null && sourceCode != "default") 
{ 
Session["sourceCode"] = sourceCode; 
ViewData["PartialView"] = "partialviewname1";    
} 
else 
{ 
ViewData["PartialView"] = "partialviewname2";     
} 
return View(); 
} 

,並在視圖中,您可以編寫代碼是這樣的:

<div> 
@Html.Partial(Convert.ToString(ViewData["PartialView"])) 
</div> 

,如果你有決定,你必須在每一個加載的局部視圖和然後你可以在全局動作過濾器中寫入以上邏輯。全局操作過濾器在任何請求的操作方法之前執行。要了解有關全局操作過濾器的更多信息,可以瀏覽此鏈接。 http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/understanding-action-filters-cs

1

如果你想顯示在所有頁面的佈局,你可能要添加的邏輯佈局文件。在那裏,你將添加類似的東西(假設剃刀)

@if(HttpContext.Current.Session["someValue"]){ 
@*render some partial*@ 
}else{ 
@*render some other partial*@ 
}