I have a DropDownList that contains “Station” codes.
@Html.DropDownList("Station", null, new { id = "dd_custom"});
The DropDownList is filled by ViewData["Station"] (list of SelectListItem).
My goal is simple: when the DropDownList CHANGES (In bold, because I know onchange exists, but cannot make it work.), I want the @ViewBag.CurrentStation to be equal to the station chosen.
What I’ve tried:
- Javascript via this website, this website, and many other websites.
- Ajax
Still, I can’t figure out how to make this dropdownlist to interact with my Controller (base Controller from the MVC4 template (Internet Application)).
The easiest way would be to interact from my index.cshtml to HomeController.cs, but I can’t figure out how.
Can someone help ?
Thanks
Edit: I need the Station Code for all my pages. The User can only modify the Station on the Home page, but I need the Station on the other page to produce reports. Global Variable would be the answer maybe, like using Application[“VarName”], but still, don’t know how to interact with my DropDownList => C# Class.
The data you store in the
ViewData,ViewBagwill exists for only one request. Say for ex. when the dropdown changes if you are making a request to server and set the new value to@ViewBag.CurrentStationbut that won’t be available for the next request because it’s gone.If you want to call some controller action when the dropdown changes you could do that through ajax using jquery.
To submit the selected value of dropdown to server you can refer this thread.
If you want the current station to be persisted for more than one request for an user then you can use session.
Server-Side
Client-Side