2012-10-30 45 views
1

我使用Directoryservices在我的頁面中登錄。我需要將用戶名傳遞給我的主頁面以在所有頁面中顯示用戶名。
如何將Viewdata值傳遞給Razor MVC4中的主頁面

我得到了用戶名並將其存儲在ViewData中。如何在masterpage中傳遞viewdata值。
我的代碼:

[HttpPost] 
    public ActionResult Index(LoginModels model) 
    { 
     if (ModelState.IsValid) 
     { 
      string DisplayUserName = string.Empty; 
      string LoginUser = model.Userid; 
      string LoginPassword = model.Password;  
      string name = model.UserName 
      if (ValidateActiveDirectoryLogin(LoginUser, LoginPassword, out DisplayUserName) == true) 
      { 
       model.UserName = DisplayUserName; 
       ViewData["UserName"] = "Welcome" + DisplayUserName; 
       return RedirectToAction("Index", "MPP", new { UserID = LoginUser }); 
      }   
      else 
      { 
       ModelState.AddModelError("","Invalid Username or Password"); 
      }    
     } 
     return View();   
    } 

在佈局頁:

@{ @ViewData["UserName"] } 


我嘗試以下方法來顯示用戶名。但它會拋出無奈之感。
編輯:

@foreach (var m in IEnumerable<SampleECommerce.Models.LoginModels>)ViewData["UserName"]) 
{ 
    @m.UserName 
} 

回答

3

有一些誤解,比如將ViewData["UserName"]爲一個字符串值,你會得到一個IEnumerable<SampleECommerce.Models.LoginModels>。這裏是另一種解決方案:

把這個頁面佈局:

<span>@{Html.RenderAction("actionname", "controllername");}</span> 

以及相關行動:

public ActionResult actionname() { 
     string result = getusername(); 
     return Content(result); 
    } 


[NoneAction] 
private string getusername(){ 
    return (Membership.GetUser()!= null) ? Membership.GetUser().UserName : "Guest"; 
} 
0

嘗試沒有多餘的@,即

@{ ViewData["UserName"] } 
+0

雖然不需要,但仍然可以在額外的@ – mattytommo

+0

之前使用ViewData之前沒有@,它會拋出錯誤 – kk1076

0

你需要你的語法變更爲杉杉:

@(ViewData["UserName"]) 

這可能是最好的(,壞的一羣)。實際上,您應該通過控制器的User屬性(通常在授權屬性中可能會讀取cookie)將您的用戶推入您網頁的User屬性 - 這樣您就不會依賴類型不安全ViewData和魔法字符串,你將要使用的東西每頁

但無論如何......如果視圖正在渲染,因爲最後一行return View();行,那麼如果你改變你的語法,你所要做的將會工作,如我所示。

如果沒有,當你這樣做return RedirectToAction("Index", "MPP", new { UserID = LoginUser });,那麼你需要的用戶名推入TempData然後在Index動作開始時讀回您的MPP控制器上它是:

所以:

TempData["UserName"] = "Welcome " + DisplayUserName; 
return RedirectToAction("Index", "MPP", new { UserID = LoginUser }); 

然後在你Index方法的開始,你需要拉值回出TempData

public class MPPController { 
    public ActionResult Index(){ 
    ViewData["UserName"] = TempData["UserName"]; 
    } 
} 

爲什麼你必須這樣做?由於RedirectToAction不會呈現頁面 - 它告訴客戶端向新的Url發出不同的請求 - 因此,任何ViewData或模型或任何被丟棄的內容就服務器而言。TempData是否提供之間的臨時存儲只有兩個連續請求 - 因此它適用於RedirectToAction方案。

就像我說的那樣 - 這實際上是一種糟糕的方式來持續從控制器查看您的用戶信息,並且您應該認真重新考慮它作爲緊急事項。

0

在頁面佈局:

<span>@{Html.RenderAction("actionname", "controllername");}</span> 

在控制器存儲中的會話變量

[HttpPost] 
public ActionResult Index(LoginModels model) 
{ 
     Session["username"] = model.UserName; 
    //remaining code 
} 

添加更多的功能

public ActionResult actionname() { 

    return Content(Session["username"]); 
} 

所以在這裏我們不需要額外的功能。

相關問題