ViewBag Usage-ASP.NET MVC3 - c#

In my controller say ControllerFirst I am setting a ViewBag property by the below line.
ViewBag.PreviousPage="ThisIsComingFromControllerFirst";
return RedirectToAction("ControllerSecond", "Home");
Now from here:
public ActionResult ControllerSecond()
{
return View();
}
I am trying to use Viewbag in the ControllerSecond by the following
View: ControllerSecond.cshtml
#if(ViewBag.PreviouPage == "SomeValue")
{
//do this
}
But ViewBag.PreviousPage value is null.
Please let me know why its null, what could I do to get the value in my view from the ControllerFirst.
I have done this one using Session, but We don't want to sessions..
Any other options?

To answer your first question, ViewBag is a more convenient form of ViewData that uses dynamic objects rather than generic ones. As with ViewData, ViewBag only exists for the life of a single request, thus it is only available between the ActionMethod and it's view. It is not available between different ActionMethods.
Think of it like an intercom system in a home. You can send messages to other parts of the home, but you can't send a message to a neighbors home.
The only other options you have are:
Use Session
Use TempData (which also uses session)
Use a Cookie
Use a querystring parameter
Use an intermediate table in your database
Post to ActionMethod

ViewBag (and ViewData) are objects for accessing extra data (i.e., outside the data model), between the controller and view.
If your data have to persist between two subsequent requests you can use TempData.
However, TempData is by default stored in the session.
So, if you don't want to use sessions, you could use cookies and somehow duplicate a bit of what session does for you, as MikeSW suggested.
When to use ViewBag, ViewData, or TempData in ASP.NET MVC 3 applications

Use TempData instead of ViewBag

You can use a cookie and somehow duplicate a bit of what session does for you.

Related

is there any alternative for session

is there any other way to save our data
in session when we save data dos not mater what is the type of it
save:
Session["instauser"] = _instaApi;
use:
var IInstaApi = Session["instauser"] as InstaApi
i know for save in db or file we should serialized the data but i cant.
because the InstaApi contain
HttpClient , HttpClientHandeler ,...
Is there any thing like session?
but keep data in db or file, not memory like session.
Update
That is private instagram api we create instant of it and login with it(no mater how!) and then if we could save that object (instants of InstaApi ) then we can use it for ever no need to login again
If its purpose is for use within controller and view of MVC, other alternatives are ViewBag, ViewData and TempData.
ViewBag and ViewData life is only for one request, while TempData can be persisted.
Take a look at APC_STORE, unlike many other mechanisms in PHP, variables stored using apc_store() will persist between requests.
http://php.net/manual/en/function.apc-store.php

Is it possible to get session values from action to another in MVC4?

Is there a way to get the values of the session in mvc4 application from the action. For example
Person to action Machine by getting the current person ID/Name ?
You can use and access Session as usual in a MVC application.
But I believe you are looking for a method to pass values from one action result to another,
You can check TempData
You can always get session values across different action methods like:
string value=Session["Name"].ToString();
Or you can use TempData to persist value across methods:
var value= TempData["key"];
TempData.Keep();

what is the scope of Viewbag in mvc3 and how do we maintain state in MVC

what is the scope of Viewbag in mvc3 is it only available on the page we are rendering through my action method.
How do we maintain information across the page in MVC. Suppose i Create new employee and and when I move to next page I want that employee information.
How do we maintain state in MVC.
the view bag is part of the httpcontext. it's primarily set in the controller action and read in the view, but it can be accessed from just about anywhere in the mvc framework within an http request/response.
the web does not have state, like you would in a rich client app. To maintain values from page to page (or more appropriately, request to request) you can use cookies, session, query string, the request body (think post/put requests).
same as #2.
ViewBag is a dynamic expression and it is available for all the pages. The data in ViewBag is the thing that changes as per we have assigned. If we are assigning ViewBag.items=itemlist; for a View, then it will be constant for that View. We can put as many data into ViewBag per page as we want like , for a single page, we can have
ViewBag.items=itemlist;
ViewBag.table=usertable;
You can maintain the information across the pages in MVC by passing the data as a parameter to the method which rendres the View on which we want to maintain the information as below:
public ActionResult CreateEmployee(EmployeeModel emp)
{
//Add Employee to db
ViewBag.employee=emp;
RedirectToAction("MethodToCall","Controller");
}
Thus the next page can have the employee information contained in the ViewBag
Alternatively, you can use ViewData as well.
3] State can be maintained using sessions, cookies etc

Returning view with model and query string

I am trying to return to view from a controller that has both querystring and model
return View("BillingReport.aspx/?report=" + fc["report_selector"], bilDet);
but this gives me a runtime error of page not found as it appends .aspx etc at the end of the url.
RedirectToAction() doesnt have an option to do it.
Is there a way to do it or does mvc3 limit us to using either a query string or a model
MVC does not support what you are looking for,
But I dont understand why do you want to Redirect To a URL with ModelValues.
Any redirection is a GET request, so you can construct the model and return View from that action.
View() expects a view name and model associated with it.
Redirect() or RedirectToAction() are used to redirect the url to another controller/action. So you can not pass a model.Even if you will try to pass model it will append model properties as querystring parameters.
Here is a reason why you would want use the model and the querystring: the querystring allows you to give user way to save URL with state information. The model allows you to pass a lot of non-flattened data around. So here is I think how to do this in MVC 5 (maybe does not work for older versions, but probably does):
Use 2 actions rather than 1 for the view. use first one to set querystring via RedirectToAction. Use second action to return model to the view. And you pass the model from the first action to the second action via session state. Here is example code:
public ActionResult Index(string email){
Session["stuff"]=Load(email);
return RedirectToAction("View1action", new { email = email, color = "red" });
}
public ActionResult View1action(string email){
return View("View1",(StuffClass)Session["stuff"]);
}
I agree with Manas's answer and if I were you I would consider changing the design if possible. As a side note, the following technique is possible:
TempData["bilDet"] = bilDet;
return RedirectToAction(....); // your controller, action etc.
On the action you can then retrieve your TempData. TempData will automatically be removed.
But also check out: ASP.NET MVC - TempData - Good or bad practice

Global Variable inside of Controller MVC

So, I have this variable that I push into the controller via POST from a form in my view.
I then push the variable into viewdata so it's available to the next view which is fine. But that view has no need of a form so I'm unable to push that same variable into the next controller. In short, it's cumbersome to push pieces of information back and forth from controller to view and reverse, so I'm looking for a way to keep a global variable alive inside a controller so that it's accessible by all action results... The general breakdown of my program is this...
-User types a "name"
-I send "name" to controller.
-I push 'name' into viewstate (query entity framework to get a list of stuff 'name'
has access to) and return that list into the view.
-In that view I can access the 'name' since it was in view state.
-Clicking on a link inside the page takes me to another controller where I need
to get access to 'name' WITHOUT passing view Routing or POST.
Obviously the easiest way would be to declare 'name' globally and then it's always available but for the life of me I can't figure out how.
Have you considered storing it in the Session?
This will allow you to easily access it, either from your controller or views, and avoids the need for global variables.
Storing:
[HttpPost]
public ActionResult YourPostMethod(string name)
{
Session["Name"] = "yourName";
}
Access: *
Make Sure to check that it exists prior to grabbing it:
var whatsMyName = (Session["Name"] != null) ? Session["Name"] : "";
Scalability Consideration
It's worth mentioning that MVC applications are designed to mimic the web and are stateless. Introducing Session variables changes this, so be aware that it can introduce issues regarding scalability, etc.
Each user that stores data within the Session will take up resources at the server level. Depending on the number of users and what you are storing within the Session, you could potentially run out of memory if those values become too large.
Why not use the session object, which is an associative array which lives while the client is connected?
$_SESSION['name'] = "zzzz"; // store session data
name = $_SESSION['name']; //retrieve data
You can use this for each user till their session is active.. hope this helps

Categories