Radio button using Viewdata for a MVC model

Asked

Viewed 470 times

1

I own a Viewdata and would like to turn it into a Radiobutton for a model

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

Radio Button :

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

But it only takes one item , I thought to make a foreach however 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.

1 answer

1

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

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

You can give yes a cast on ViewData and create Radio Buttons.

Example of how to get the user’s choice

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>
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.