0

i have this code

<select name="item.location" class="selectpicker">
    
    @foreach (var x in JournalConnector.GetAllLocations())
    {
        <option id="line" value="@x">@x</option>

    }
</select>

which gets the locations that are in the database.

after i post my form i want it to remember the selected option and start the page on it again.

the rest of the code on the page is here: JsFiddle

i have tried using localstorage and session storage, but neither saves the value i need to save (which would be @x)

ekad
  • 14,436
  • 26
  • 44
  • 46
  • Can't you just bring back the value from database and match in your HTML rather than saving it in local or session storage? – James Aug 10 '16 at 10:38
  • In your function where form procession is done, return the selected value to the view and by using that value make drop down selected. – Mayank Pandeyz Aug 10 '16 at 10:40

1 Answers1

0
<select name="item.location" class="selectpicker">

    @foreach (var x in JournalConnector.GetAllLocations())
    {           
       @if(ViewBag.SelectedID ==x.id ){
            <option id="line" selected="selected" value="@x">@x</option>
        }
        else{
            <option id="line" value="@x">@x</option>
        }
    }
</select>

this is not the exact code, but this is the idea

in the controller

save the posted id to a viewbag

ViewBag.SelectedID = ID;
Arun Prasad E S
  • 9,489
  • 8
  • 74
  • 87
  • This solution works but I'd advise against using ViewBag as it is a dynamic object and it can get quite messy. Also you could make use of the HTML Helper for DropDownLists which would simplify you code for you. Have a look at this SO answer: http://stackoverflow.com/questions/6807256/dropdownlist-set-selected-value-in-mvc3-razor – Rian Mostert Aug 10 '16 at 10:56
  • 1
    thank you for the solution, i used yours with some modifications - and now its working. – Bjørn Henneberg Aug 22 '16 at 08:28