Reputation: 9966
I have the following simple problem in ASP.NET MVC 4. I have a viewmodel with a list of options (a simple key/value list), and an object which should have the selected value.
I have the following content, where I render the list using a foreach loop and shows the value using RadioButtonFor
. But in the post, I don't get any value back.
How do I modify my code, so I can get the id of the selected option in my post?
I have the following form:
@using (Html.BeginForm("Credits","User",FormMethod.Post))
{
@Html.EditorFor(model => model.PurchaseAmount)
<div>
@foreach (var a in Model.PaymentMethods)
{
<p>
@Html.RadioButtonFor(b=>b.PaymentMethods,)
@Html.RadioButtonFor(b => b.SelectedPaymentMethod, a.Id) @a.Name
</p>
}
</div>
<div class="form-group">
<input type="submit" class="btn btn-success" value="@ViewRes.GoToPayment" />
</div>
}
I have the following viewmodel:
public class CreditsViewModel
{
public IEnumerable<PaymentMethodViewModel> PaymentMethods { get; set; }
public PaymentMethodViewModel SelectedPaymentMethod { get; set; }
public int PurchaseAmount { get; set; }
public decimal Credit { get; set; }
public decimal CreditLimit { get; set; }
}
public class PaymentMethodViewModel
{
public int Id { get; set; }
public string Name { get; set; }
}
Post code:
[HttpPost]
public ActionResult Credits(CreditsViewModel model)
{
string url = "";
//string returnUrl = orderService.AddFunds(SecurityUtility.CurrentUser.Id, model.Funds);
return Redirect(url);
}
Upvotes: 0
Views: 1937
Reputation: 11
//Model.
public class TestRadiobutton
{
public string Theme { get; set; }
}
//Controller.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
TestRadiobutton obj=null;
if (TempData["MyObj"] != null)
{
obj = (TestRadiobutton)TempData["MyObj"];
}
return View(obj);
}
[HttpPost]
public ActionResult Change(TestRadiobutton obj)
{
TempData["MyObj"] = obj;
return RedirectToAction("Index");
}
}
//view.
@model RadioButtonInMvc.Models.TestRadiobutton
@{
ViewBag.Title = "Index";
}
@using (Html.BeginForm("Change", "Home", FormMethod.Post))
{
<div class="jumbotron">
<div class="row">
<div class="col-lg-6">
@Html.RadioButtonFor(m => m.Theme, "Dark")
<span>Dark Theme</span>
</div>
<div class="col-lg-6">
@Html.RadioButtonFor(m => m.Theme, "Light")
<span>Light Theme</span>
</div>
<div>
<button type="submit" class="btn btn-primary">Save</button>
</div>
<label>@Html.DisplayFor(m => m.Theme)</label>
</div>
</div>
}
Upvotes: 1
Reputation: 12837
That should be sufficient:
@foreach (var a in Model.PaymentMethods)
{
<p>
@Html.RadioButtonFor(b => b.SelectedPaymentMethod, a.Id) @a.Name
</p>
}
Change the SelectedPaymentMethod to be int
instead of PaymentMethodViewModel
.
Also remove the PaymentMethods
from the view model and move it to the ViewBag
, this probably breaks the model binding.
Upvotes: 1