How to select value in Select

2

How to select a value other than the first according to an ASP.NET Razor C # variable.

<select id="MeetingFrequency" name="MeetingFrequency">
   <option value="0" selected disabled>Selecionar</option>
   <option value="SEMANAL">Semanal</option>
   <option value="MENSAL"> Mensal</option>
   <option value="BIMESTRAL" >Bimestral</option>
   <option value="TRIMESTRAL">Trimestral</option>
   <option value="QUADRIMESTRAL">Quadrimestral</option>
   <option value="SEMESTRAL">Semestral</option>
   <option value="ANUAL">Anual</option>
</select>
    
asked by anonymous 21.07.2017 / 14:19

3 answers

2

Well once I've used something like this, see if it helps!

@{  
bool[] select = new bool[2];
for (int i = 0; i < 2; i++)
{
select[i] = false;
}
if(model.valor != null)
 switch (model.valor.ToString())
{
 case "SEMANAL": select[0] = true; break;
 case "MENSAL": select[1] = true; break;
 }
 }
}
<select id="MeetingFrequency" name="MeetingFrequency">
<option value="0"selected disabled>Selecionar</option>
<option value="SEMANAL"selected=@select[0]>Semanal</option>
<option value="MENSAL" selected=@select[1]> Mensal</option>
</select>

Give one adapted to your need

    
03.08.2017 / 16:05
2

To keep a default value in the <select> component you should use the <selected> property in <option>

Use this mail!

<option value="audi" selected>Audi</option>

See in the first line of the option of your <select> component you are already using the <selected> property so it is selected!

See Example

    
21.07.2017 / 19:25
2

Can be done with Razor via DropDownListFor and SelectList .

 @Html.DropDownListFor(model => model.Variavel, new SelectList(Model.ListaVariavel, "Value", "Text", Model.Variavel), "Selecione")

In the code, if model.Variavel has value, it will set the value for you. If you need another value, put it in the Model.Variavel (third parameter of the selectlist)

I suggest you see SelectList and #

25.07.2017 / 17:02