MVC3 DropDownListFor - ¿un ejemplo sencillo?


Estoy teniendo problemas con DropDownListFor en mi aplicación MVC3. Pude usar StackOverflow para averiguar cómo hacer que aparezcan en la vista, pero ahora no sé cómo capturar los valores en sus propiedades correspondientes en el Modelo de vista cuando se envía. Para que esto funcionara tuve que crear una clase interna que tuviera un ID y una propiedad value, luego tuve que usar un IEnumerable<Contrib> para satisfacer los requisitos del parámetro DropDownListFor. Ahora, sin embargo, ¿cómo se supone que MVC FW mapee el valor que es seleccionado en este menú desplegable de nuevo en la propiedad simple string en mi modelo de vista?

public class MyViewModelClass
{
    public class Contrib
    {
        public int ContribId { get; set; }
        public string Value { get; set; }
    }

    public IEnumerable<Contrib> ContribTypeOptions = 
        new List<Contrib>
        {
            new Contrib {ContribId = 0, Value = "Payroll Deduction"},
            new Contrib {ContribId = 1, Value = "Bill Me"}
        };

    [DisplayName("Contribution Type")]
    public string ContribType { get; set; }
}

En mi opinión pongo el menú desplegable en la página de esta manera:

<div class="editor-label">
    @Html.LabelFor(m => m.ContribType)
</div>
<div class="editor-field">
    @Html.DropDownListFor(m => m.ContribTypeOptions.First().ContribId, 
             new SelectList(Model.ContribTypeOptions, "ContribId", "Value"))
</div>

Cuando envío el formulario, ContribType es (por supuesto) null.

¿Cuál es la manera correcta de hacer esto?

Author: fubo, 2011-08-22

4 answers

Usted debe hacer así:

@Html.DropDownListFor(m => m.ContribType, 
                new SelectList(Model.ContribTypeOptions, 
                               "ContribId", "Value"))

Donde:

m => m.ContribType

Es una propiedad donde estará el valor del resultado.

 160
Author: Sergey Gavruk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-19 04:02:04

Creo que esto ayudará : En el controlador obtener los elementos de la lista y el valor seleccionado

public ActionResult Edit(int id)
{
    ItemsStore item = itemStoreRepository.FindById(id);
    ViewBag.CategoryId = new SelectList(categoryRepository.Query().Get(), 
                                        "Id", "Name",item.CategoryId);

    // ViewBag to pass values to View and SelectList
    //(get list of items,valuefield,textfield,selectedValue)

    return View(item);
}

Y en Vista

@Html.DropDownList("CategoryId",String.Empty)
 7
Author: Praveen M P,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-02 14:40:07

Para enlazar Datos dinámicos en una lista desplegable, puede hacer lo siguiente:

Crear ViewBag en el controlador como a continuación

ViewBag.ContribTypeOptions = yourFunctionValue();

Ahora use este valor en la vista como a continuación:

@Html.DropDownListFor(m => m.ContribType, 
    new SelectList(@ViewBag.ContribTypeOptions, "ContribId", 
                   "Value", Model.ContribTypeOptions.First().ContribId), 
    "Select, please")
 6
Author: Dilip0165,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-14 13:18:19
     @Html.DropDownListFor(m => m.SelectedValue,Your List,"ID","Values")

Aquí el valor es el objeto del modelo donde desea guardar el Valor seleccionado

 0
Author: Abdul Aleem,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-20 18:16:40