在剃须刀动态单选按钮 [英] dynamic radiobutton in razor

查看:109
本文介绍了在剃须刀动态单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用剃须刀视图引擎,并有一点麻烦创建单选的列表。

I am using razor view engine and having a bit of trouble creating a list of radiobutton.

我填充了 A表与我的模型,我认为值循环。
在每一行我想有一个单选。我希望能够选择只有一个行并从模型中获取相关项目ID,并提交到另一页。我知道如何发布。其实,我用复选框做到了这一点。但随着复选框的问题是,它允许多个选择。

I am populating a table with a for loop with the values of my model in my view. at each row I want to have a radiobutton. I want to be able to select just one row and get the related items id from the model and submit it to another page. I know how to post. I actually achieved this by using checkbox. But the problem with checkbox is that it allows multiple selection.

所以我想我需要使用单选。任何帮助将是AP preciated。

So I guess I need to use radiobutton. Any help would be appreciated.

推荐答案

假设你有一个视图模型像这样

Assuming you have a ViewModel like this

public Class CheckOutViewModel
{
  public string SelectedPaymentType { set; get; }
  public IEnumerable<SelectItems> PaymentTypes { set; get; }
}

和你在你的 GET Action方法设置PaymentTypes收集并发送至该是强类型为 CheckOutViewModel

And you are setting the PaymentTypes Collection in your GET Action method and sending it to the view which is strongly typed to CheckOutViewModel

public ActionResult Checkout()
{
  var vm=new CheckOutViewModel
  vm.PaymentTypes=GetPaymentTypes(); //gets a list of SelectItems
  return View(vm);
}

而在你的视图

@model CheckOutViewModel
@using(Html.BeginForm())
{
  foreach (var paymentItem in Model.PaymentTypes)
  {
    @Html.RadioButtonFor(mbox => mbox.SelectedPaymentType, 
                                              paymentItem.ID.ToString())       
    @paymentItem.Name    
  }
  <input type="submit" value="Save" />
}

假设 GetPaymentTypes()方法将返回在数据库中的记录一个SelectItems 的列表。

Assuming GetPaymentTypes() method will return a list of SelectItems for your records in the database.

这会给你同名的值(SelectedPaymentType)单选按钮。所以只有一个可以被选中。

This will give you the Radio buttons with the same name value(SelectedPaymentType). so only one can be selected.

在你的 POST 的动作,你可以通过检查SelectedPaymentType属性值读取所选值

In your POST action, you can read the selected value by checking the SelectedPaymentType property value

[HttpPost]
public ActionResult Checkout(CheckOutViewModel model)
{
  //check the value of model.SelectedPaymentType

}

这篇关于在剃须刀动态单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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