kk1076
kk1076

Reputation: 1748

How to pass Viewdata value to masterpage in Razor MVC4

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
} 

Upvotes: 1

Views: 8807

Answers (4)

user3501613
user3501613

Reputation: 610

in layout page:

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

in controller store a session variable

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

add one more function

public ActionResult actionname() {

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

so here we dont need additional functions.

Upvotes: 0

Saeid
Saeid

Reputation: 13582

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";
}

Upvotes: 4

Andras Zoltan
Andras Zoltan

Reputation: 42333

Firs you need to change your syntax to:

@(ViewData["UserName"])

That's probably the best (of a bad bunch). Realistically you should be looking to push your user into the User property of your pages via the User property of your controllers (typically in an authorization attribute where, perhaps, you read a cookie) - that way you don't rely on type-unsafe ViewData and magic strings for something that you're going to be using on every page.

But anyway... if the view is rendering because of the last return View(); line then what you're trying to do will work if you change your syntax as I've shown.

If not, and it's when you do return RedirectToAction("Index", "MPP", new { UserID = LoginUser }); then you need to push the UserName into TempData and then read it back at the start of the Index action on your MPP controller:

So:

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

And then at the start of your Index method you need to pull the value back out of TempData:

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

Why do you have to do this? Because RedirectToAction doesn't render a page - it tells the client to make a different request to a new Url - thus any ViewData or model or whatever is thrown away as far as the server is concerned. TempData is there to provide temporary storage between two successive requests only - thus it works well for the RedirectToAction scenario.

Like I say though - this really is a poor way to persist your user information from controller to view and you should seriously rethink it as a matter of urgency.

Upvotes: 0

Justin Harvey
Justin Harvey

Reputation: 14672

Try it without the extra @, i.e.

   @{  ViewData["UserName"]   }

Upvotes: 0

Related Questions