我使用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
}
雖然不需要,但仍然可以在額外的@ – mattytommo
之前使用ViewData之前沒有@,它會拋出錯誤 – kk1076