0

I am using the regular html drop downlist (select) in a View. I don't want to use Html.DropdownlistFor for some reason. Now I am able to get the selected value in my Controller class. How do I assign back a selected value back to the view?

<select name='ddlLocation' id='ddlLocation'>
  <option value="">All </option>
  <option selected="selected" value="1">City1</option>
  <option value="2">City2</option>
  <optgroup label="Group">
    <option value="3">City2</option>
    <option value="4">City3</option>
    <option value="5">City4</option>
  </optgroup>
</select>
tereško
  • 58,060
  • 25
  • 98
  • 150
pili
  • 795
  • 2
  • 10
  • 24

2 Answers2

1

Well there you go, you've already done it by using the selected attribute:

<option selected="selected" value="1">City1</option>

You should put the selected attribute on the value you want to be preselected.

I guess that now you realize your madness of not using the Html.DropDownListFor helper which automatically handles that for you. Because now you're gonna have to put @if else stataments turning your view into spaghetti code in order to achieve the desired behavior. But I guess you've got your reasons for not using the helper.


UPDATE:

From your comment it seems that your reason for not using the DropDownList helper is because it doesn't support optgroup. That's true and a good reason. But writing a custom helper is trivial and would really avoid you from spaghettifying your views with if/else statements for preselecting the default value.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • The reason I am not using DropDownListFor is because it does not support optgroup. But i am looking for a simple html based solution to set the default value instead of spaghetti code. Using get,post, server variables like php... – pili Aug 28 '13 at 20:34
  • You will have to set the selected attribute over the proper option. In order to do that you will unavoidably need to write if statements in your view. – Darin Dimitrov Aug 28 '13 at 20:39
  • I believe returning a select list with selected value from a server side code should be very much possible. There should be a html concept do this instead of using a server side language feature. – pili Aug 28 '13 at 20:40
  • Well actually Razor is server side code. Really don't waste your time with this, just use a custom helper. – Darin Dimitrov Aug 28 '13 at 20:41
1

There aren't many clean ways to go about this, but assuming you have some type of model bound to this page, you could set the selected value of the drop down based on the model value, as soon as the page loads :

<script type="text/javascript">

(function($) {
    $(document).ready(function() {
        var locationToSet = "@Model.LocationToSet";
        $('#ddlLocation option[value="' + locationToSet + '"]').prop('selected', true);});
})(jQuery);​

</script>
X3074861X
  • 3,709
  • 5
  • 32
  • 45