避免在MVC视图的mv单选按钮中使用编辑器模板进行foreach [英] Avoid foreach using Editor Template in mv radiobutton within an mvc view
问题描述
我试图避免在mvc视图中使用foreach,正如我在很多答案中所看到的那样,这是一个好习惯.但是我并没有完全了解如何实现它.
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.
我想使用银行列表,创建一堆单选按钮,以便发布其中一个(实际上是id)
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)
成为视图模型:
public class CashbackOfferViewModel
{
...
public string DepositBank { get; set; }
public IEnumerable<CompanyBank> DepositBanks { get; set; }
}
我想使用类似的东西:
@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(????)
如何将其绑定到模型中的DepositBank属性?
How do I bind it to the DepositBank property in the model??
更新:
我一直在努力使这项工作可行,但以当前情况为准
I've been trying to make this work but with the current situation
Viewmodel:
Viewmodel:
public class CashbackOfferViewModel
{
....
public string DepositBankCode { get; set; }
public IEnumerable<CompanyBank> DepositBanks { get; set; }
}
EditorTemplate;
EditorTemplate;
@model CompanyBank
<tr>
<td>
@Html.RadioButtonFor(m => m.CompanyBankCode, Model.CompanyBankCode)
<span>@Html.LabelFor(m => m.CompanyBankName, Model.CompanyBankName)</span>
</td>
</tr>
但是我要在加载时检查所有单选按钮,实际上生成的html是这个(更改每个按钮的id)
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)
代替此
@foreach (var depositBank in Model.DepositBanks)
{
@Html.RadioButtonFor(m => m.DepositBankCode , depositBank.CompanyBankCode)
}
推荐答案
您只需要引用要绑定的属性名称
you just need to reference the property names you want to bind
@model CompanyBank
@Html.RadioButtonFor(x => x.PropertyName)
@Html.LabelFor(x => x.PropertyName)
请确保您将视图命名为CompanyBank.cshtml,因为在IEnumerable中无法定义编辑器视图名称.
make sure that you name your view CompanyBank.cshtml because in IEnumerable you cannot define the editor view name.
这篇关于避免在MVC视图的mv单选按钮中使用编辑器模板进行foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!