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.
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
}