0

I have the selected code of a property in a model and the descripcion in another one, i'm trying to show in my view the description, not the code, i am populating the list from a diferent database table and trying to set the selected value from the model used in the view.

This is my View

IEnumerable<SelectListItem> listaMotivos = (IEnumerable<SelectListItem>)ViewBag.motivosFinalizacion;   

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Win_User_ID)
        </td>            
        <td>                                
            @Html.DropDownListFor(modelItem => item.Motivo_Finalizacion, listaMotivos, "", htmlAttributes: new { @class = "form-control", @id = "IndexSalarioVendedor" })
        </td>
    </tr>
}

My list is populate in the controller by:

public void cargarMotivosFinalizacion()
{
    ViewBag.motivosFinalizacion = db.SFI_AtributosDbSet.Where
    (x => x.Tipo_Atributo == "MOTIVO FINALIZACION").OrderBy(x => 
    x.Descrip_Atributo).Select(x => new SelectListItem
    {
          Text = x.Descrip_Atributo,
          Value = x.ID_Atributo
     }).ToList();
}

I need to set the code selected in the dropdownlist from model but is not working

  • Firstly, your cannot use a `foreach` loop to generate form controls for a collection (refer [this answer](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943). Second you have not shown what `listaMotivos` is. Third, `Motivo_Finalizacion` is a `ViewBag` property which is type of `IEnumerable` which makes no sense (a ` –  Oct 08 '17 at 00:25
  • Sorry, i've just added what is listaMotivos, and sorry but i don't understand, maybe i couldn't explain. Is there a way to do what i'm trying? I need to show the "Text" instead of "Value" which is set in my model – Valentina Oppen Oct 08 '17 at 00:38
  • I do not know what you mean by _show the "Text" instead of "Value" which is set in my model_ - you have not even shbown your model. But there are so many fundamental errors with your code. Read the dupe, and the link in the previous comment and [this one](http://stackoverflow.com/questions/37161202/will-there-be-any-conflict-if-i-specify-the-viewbag-name-to-be-equal-to-the-mode/37162557#37162557) as well –  Oct 08 '17 at 01:53

0 Answers0