Dynamic Radiobutton In Razor
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
Solution 1:
Assuming you have a ViewModel like this
public Class CheckOutViewModel
{
publicstring 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 SelectItemsreturn 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
}
Post a Comment for "Dynamic Radiobutton In Razor"