Avoid foreach using Editor Template in mv radiobut

2019-05-22 22:54发布

问题:

I'm trying to avoid using a foreach inside an mvc view, as I've seen in quite a few answers it's a good practice. But I'm not exactly getting how to achieve it.

I would like to use a list of banks, to create a bunch of radio buttons in order to post one of them (it's id, actually)

Being the viewmodel:

public class CashbackOfferViewModel
{
    ...
    public string DepositBank { get; set; }
    public IEnumerable<CompanyBank> DepositBanks { get; set; } 
}

I would like to use something like:

@Html.EditorFor(m => m.DepositBanks)

and that would create the appropriate radio buttons. But when creating the editor template if I use the model

@model CompanyBank

@Html.RadioButtonFor(??????)
@Html.LabelFor(????)

How do I bind it to the DepositBank property in the model??

UPDATE:

I've been trying to make this work but with the current situation

Viewmodel:

public class CashbackOfferViewModel
{
    ....
    public string DepositBankCode { get; set; }
    public IEnumerable<CompanyBank> DepositBanks { get; set; } 
}

EditorTemplate;

@model CompanyBank

<tr>
  <td>
      @Html.RadioButtonFor(m => m.CompanyBankCode, Model.CompanyBankCode)
      <span>@Html.LabelFor(m => m.CompanyBankName, Model.CompanyBankName)</span>
  </td>
</tr>

But I'm getting all the radio buttons checked on load, actually the html generated is this one (changing the id for each of them)

<input checked="checked" id="DepositBanks_0__CompanyBankCode" name="DepositBanks[0].CompanyBankCode" type="radio" value="HBOS">

Basically I would like to use this in the view:

@Html.EditorFor(m => m.DepositBanks)

instead of this

@foreach (var depositBank in Model.DepositBanks)
{
    @Html.RadioButtonFor(m => m.DepositBankCode , depositBank.CompanyBankCode)
}

回答1:

you just need to reference the property names you want to bind

@model CompanyBank


@Html.RadioButtonFor(x => x.PropertyName)
@Html.LabelFor(x => x.PropertyName)

make sure that you name your view CompanyBank.cshtml because in IEnumerable you cannot define the editor view name.