How to leave the selected value using html.dropdowlist in MVC C # with aspx engine, similar to razor

0

I have the following definition of list of options:

 <% dynamic listItems_Afirmacion = new List<ListItem> {
                    new ListItem {
                        Text = "Si",
                        Value = "S"},
                    new ListItem {
                        Text = "No",
                        Value = "N"
                    },
     };
  %>

<table>
  <thead>
    <tr>
        <th>opcion<th>
    </tr>
</thead>    
<tbody>
    <% foreach (var item in Model)
       { %>
    <tr>
        <td>
         <%:Html.DropDownList("afirmacion", new SelectList(listItems_Afirmacion, "Value", "Text"),"Seleccione", new {@class = "form-control input-sm"})%>
       </td>
  <tr>
 ......

but I want to leave the selected value S or N depending on the value it brings. The field to access is item.valor , which I imagine somewhere you should indicate it to leave selected ( selected ). I would like to know how to do it?

    
asked by Danilo 06.01.2017 в 02:22
source

2 answers

1

You could use something like being

<% (int i = 0; i < Model.Count; i++)
       { %>
    <tr>
        <td>
         <%:Html.DropDownListFor(m=> m[i].valor, new SelectList(listItems_Afirmacion, "Value", "Text"),"Seleccione", new {@class = "form-control input-sm"})%>
       </td>
  <tr>

You will see that it changes by a for to have the index of the collection that then use in Html.DropDownListFor(m=> m[i].valor, ...)

If you want to use the foreach you can also but you will need a variable that you increase in each iteration

    
answered by 16.02.2017 в 11:50
1

Consider using SelectList that would help you with one of its builders.

Assuming the model is a listing (in my case a chain list).

public ActionResult Index()
{
    var items = new[]
    {
        "S", "N"
    };

    return View(items);
}

Would consider using:

@{
    foreach (var item in Model)
    {
        @Html.DropDownList("Afirmación", new SelectList(listItems_Afirmacion, "Value", "Text", item), "Seleccione", new { @class = "form-control input-sm" })
    }
}

The rendering time generates:

<select class="form-control input-sm" id="Afirmaci_n" name="Afirmación">
    <option value="">Seleccione</option>
    <option selected="selected" value="S">Si</option>
    <option value="N">No</option>
</select>

<select class="form-control input-sm" id="Afirmaci_n" name="Afirmación">
    <option value="">Seleccione</option>
    <option value="S">Si</option>
    <option selected="selected" value="N">No</option>
</select>
    
answered by 16.02.2017 в 15:40