When we are working on our project, several situations and challenges may come. We need to face all these situations, sometime small problems may take 1 to 2 hours. After spending this much of precious time we think this could have been implemented in 5 minutes, but why we spent 1 to 2 hours?
So today I am explaining a simple problem which could help you to save time while coding. This is a small and simple problem.
Could we use a session object in our view?
Answer- The answer is yes.
Let me explain how, I can use it and retrieve it in my view.
This is my HomeController and I have the following method, where I have saved my name in a session variable.
- public ActionResult Employee()
- {
- Session["username"] = "debendra Prasad Dash";
- return View();
- }
Now, retrieve this variable in any view.
So this is very simple.
Go to the view where you want to retrieve the value of session. Add a Hidden field there like this:
- <input type="hidden" value="@Session["username"]" id="myHiddenVar" />
Here the value will be my session value.
Write a simple jQuery to display the value on any button click or anything like this:
- var x = $('#myHiddenVar').val();
- $('#displayname').val(x.toString());
So this is the simple way to retrieve a session object in a view.