Radio button using ViewData for an MVC model

1

I have a ViewData and would like to make it a RadioButton for a model

ViewData["tiposPagamento"] = dbo.TiposPagamento.Where(_=>_.Ativo);

Radio Button:

  @Html.RadioButton(m=>m.TipoPagamentiID, ViewData["tiposPagamento"])

But just get an item, I thought about doing a foreach but as it is a viewData would have to do a cast.    And I would like to know how to select the one chosen by the user.

    
asked by anonymous 16.04.2015 / 12:43

1 answer

1

@Html.RadioButton() does not accept a Collection.

To have something like RadioButtonList you would have to implement a helper.

You can instead cast a cast on ViewData and create the Radio Buttons.

Example of getting the one chosen by the user

ViewData["tiposPagamento"] = dbo.TiposPagamento.Where(_ => _.Ativo)
    .Select(e => new SelectListItem 
    { 
        Value = e.Id, 
        Text = e.Nome, 
        Selected = pagamentoSelecionadoId == e.Id 
    });

foreach (var item in ViewData["tiposPagamento"] as IEnumerable<SelectListItem>)
{
    <div>
        @Html.RadioButtonFor(e => e.TipoPagamentoId, item.Value) @item.Text
    </div>
}
    
16.04.2015 / 13:35