dynamic radiobutton in razor

那年仲夏 提交于 2019-12-24 06:49:01

问题


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

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.

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


回答1:


Assuming you have a ViewModel like this

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

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);
}

And in your View

@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" />
}

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

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

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

}


来源:https://stackoverflow.com/questions/11848762/dynamic-radiobutton-in-razor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!