0

I am working on an asp.net application. I have a viewbag with a boolean result (true or false) and I need to select one option from a razore view using this viewbag. I have done it like this.

Controller:

ViewBag.AMZ = result.shipment.ShipAMZ ;

View:

 @{
   var IsAmzSelected = (bool)ViewBag.AMZ;
   }
<select id="amz" name="amz" class="form-input"> 
                           @if (IsAmzSelected == true)
                           {
                            <option value='1' selected>AMZ</option>
                            <option value='0'>BBW</option>
                           }
                           else
                           {
                            <option value='1'>AMZ</option>
                            <option value='0' selected>BBW</option>
                           }                               
                            </select>

I tried using Html dropdownlist helper method but it didn't work.

in controller i did it like this:

 ViewBag.AMZ = new SelectList(new List<SelectListItem>() { new SelectListItem() { Text = "AMZ", Value = "1" }, new SelectListItem() { Text = "BBW", Value = "0",Selected=true } }, "Value", "Text" , result.shipment.amz);

and then bound it to htmldropdown to this viewbag but it didn't work

Can you please suggest how to do it using html.dropdown?

Asif Hameed
  • 1,353
  • 9
  • 25
  • 46
  • 1
    Why in the would are you not using a model and binding to your model? And why a manual ` –  Aug 01 '17 at 00:58
  • I don't know what will be razor syntax in my case for this viewbag: ViewBag.AMZ = new SelectList(new List() { new SelectListItem() { Text = "AMZ", Value = "1" }, new SelectListItem() { Text = "BBW", Value = "0",Selected=true } }, "Value", "Text" , result.shipment.amz); – Asif Hameed Aug 01 '17 at 01:12
  • First creating a 2nd identical `IEnumerable` from the forst one using `new SelectList(...)` is pointless. You need a property to bind to (say) `int SelectedValue` and the its `@Html.DropDownListFor(m => m.SelectedValue, (IEnumerable)ViewBag.AMZ)` and if `SelectedValue=0` then the first option will be selected, and if `SelectedValue=1` then the 2nd will be. –  Aug 01 '17 at 01:16
  • But do not use `ViewBag` - use a view model with a `IEnumerable` property (see also [this answer](https://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system-int32-but-must-be-o)) –  Aug 01 '17 at 01:16

0 Answers0