I use Directoryservices for login in My page. I need to pass the username to my masterpage to display the username in all the pages.
I got the username and stored it in a ViewData. How to pass the viewdata value in masterpage.
My code :
[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();
}
In Layout page :
@{ @ViewData["UserName"] }
I tried the following way to display the Username. But it throws nullexception.
EDIT :
@foreach (var m in IEnumerable<SampleECommerce.Models.LoginModels>)ViewData["UserName"])
{
@m.UserName
}
There are some misunderstandings, like if you set ViewData["UserName"]
to a string value you get a IEnumerable<SampleECommerce.Models.LoginModels>
. Here is another solution:
Put this to layout page:
<span>@{Html.RenderAction("actionname", "controllername");}</span>
And in related action:
public ActionResult actionname() {
string result = getusername();
return Content(result);
}
[NoneAction]
private string getusername(){
return (Membership.GetUser()!= null) ? Membership.GetUser().UserName : "Guest";
}