避免在 mvc 视图中使用 mv 单选按钮中的编辑器模板进行 foreach [英] Avoid foreach using Editor Template in mv radiobutton within an mvc view

查看:27
本文介绍了避免在 mvc 视图中使用 mv 单选按钮中的编辑器模板进行 foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图避免在 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

视图模型:

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

编辑器模板;

@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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆