0

Hi I am developing an application in MVC3. and i am stuck at one place.

I have 2 fields in my view which are not a part of my class. i am just using them to populate the dropdown The 2 fields are State and District. But i want to show the selected value of the two fields in another View.

I tried it using ViewBag but this doesnot work and gives me Null.

this is inside Create get method:

int stateid = Convert.ToInt32(formcollection["ProvincialState.ProvincialStateID"]);
int districtid =  Convert.ToInt32(formcollection["District.DistrictID"]);

ProvincialState state = new AddressService().FetchStateByStateId(stateid);
District district = new  AddressService().FetchDistrictByDistrictId(districtid);

ViewBag.State = state.ProvincialStateName;
ViewBag.District = district.DistrictName;

and this is inside Details View:

 string data1 = ViewBag.State;
 string data2 = ViewBag.District;
 ViewBag.State = data1;
 ViewBag.District = data2;

I cannot use post method of Create coz i need to show this data only on another view. or if is their any method thru which i can show the data in the same view.

user1274646
  • 921
  • 6
  • 21
  • 46

2 Answers2

4

ViewBag is like ViewData. In order to have information between pages you should store that info in session. You can do that in 2 ways:

Use a session variable like:

this.Session["SessionVariable"] = value;

Or use the this.TempData object:

this.TempData["SessionVariable"] = value;

The difference between this two is that the TempData object will be deleted from the session when it is read.

TempData is just a wrapper of the session.

Fabio Milheiro
  • 8,100
  • 17
  • 57
  • 96
0

You can send this fields to your action in addition to model, and then store it in session for example:

public class SomeController: Controller
{
    [HttpPost]
    public ActionResult DoSomething(MyModel model, int state, int district)
    {
        // validating model...
        // ...

        Session["state"] = state;
        Session["district"] = district;
        // some other logic...
    }
}