MVC 4 Razor 中的多个单选按钮组 [英] Multiple radio button groups in MVC 4 Razor

查看:21
本文介绍了MVC 4 Razor 中的多个单选按钮组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表单中需要有多个单选按钮组,如下所示:

I need to have multiple radio button groups in my form like this:

我知道只需为每个组指定相同的名称"html 属性即可完成.
但是
MVC 不允许您在使用 html helper 时指定自己的 name 属性,如下所示:

I know it's simply done by specifying the same "name" html attribute for each group.
HOWEVER
MVC doesn't let you specify your own name attribute when using html helper like this:

@Html.RadioButtonFor(i => item.id, item.SelectedID, new { Name = item.OptServiceCatId })  

因为它查看每个标签的name"属性(而不是id")以将表单映射/绑定到模型控制器接收等

Because it looks at each tag's "name" attribute (not "id") to map/bind the form to the model which the controller receives, etc.

有人说为每个指定相同的GroupName"属性可以解决问题,但它也不起作用.

Some said that specifying each with the same "GroupName" attribute will solve the problem, but it didn't work either.

那么,有什么方法可以奏效吗?

So, is there any way which works ?


这是我的观点(简化):


Here's my view (simplified):

@model Service_Provider.ViewModels.SelectOptServicesForSubServiceViewModel

@foreach (var cat in Model.OptServices)
{
  //A piece of code & html here
  @foreach (var item in cat.OptItems.Where(i => i.MultiSelect == false))
  {
     @Html.RadioButtonFor(i => item.id, item.SelectedID, new { GroupName = item.OptServiceCatId })
<br />
  }    
}

注意:
我的模型是一个 List:

public List<OptServices> Cats {get; set;}

并且 OptServices 里面有一个 OptItemsList:

And OptServices has a List of OptItems inside:

public class OptServices
{
//a few things
public List<OptItems> Items {get; set;}
}

推荐答案

好的,我是这样解决这个问题的

Ok here's how I fixed this

我的模型是类别list.每个类别都包含其子类别list.
考虑到这一点,每次在 foreach 循环中,每个 RadioButton 都会将其类别 ID(这是唯一的)作为其名称属性.
而且我还使用了 Html.RadioButton 而不是 Html.RadioButtonFor.

My model is a list of categories. Each category contains a list of its subcategories.
with this in mind, every time in the foreach loop, each RadioButton will have its category's ID (which is unique) as its name attribue.
And I also used Html.RadioButton instead of Html.RadioButtonFor.

这是最终的工作"伪代码:

Here's the final 'working' pseudo-code:

@foreach (var cat in Model.Categories)
{
  //A piece of code & html here
  @foreach (var item in cat.SubCategories)
  {
     @Html.RadioButton(item.CategoryID.ToString(), item.ID)
  }    
}

结果是:

<input name="127" type="radio" value="110">

请注意,我没有将所有这些单选按钮组放入表单中.而且我不知道这个解决方案是否仍然可以在表单中正常工作.

Please note that I HAVE NOT put all these radio button groups inside a form. And I don't know if this solution will still work properly in a form.

感谢所有帮助我解决这个问题的人;)

Thanks to all of the people who helped me solve this ;)

这篇关于MVC 4 Razor 中的多个单选按钮组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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