我在ASP.NET MVC 4中遇到以下简单问题。我有一个带有选项列表的viewmodel(一个简单的键/值列表),以及一个应该具有所选值的对象。
我有以下内容,我使用foreach循环渲染列表,并使用RadioButtonFor
显示值。但在帖子中,我没有得到任何回报。
如何修改我的代码,以便在帖子中获取所选选项的ID?
我有以下表格:
@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>
}
我有以下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; }
}
邮政编码:
[HttpPost]
public ActionResult Credits(CreditsViewModel model)
{
string url = "";
//string returnUrl = orderService.AddFunds(SecurityUtility.CurrentUser.Id, model.Funds);
return Redirect(url);
}
答案 0 :(得分:1)
这应该足够了:
@foreach (var a in Model.PaymentMethods)
{
<p>
@Html.RadioButtonFor(b => b.SelectedPaymentMethod, a.Id) @a.Name
</p>
}
将SelectedPaymentMethod更改为int
而不是PaymentMethodViewModel
。
同时从视图模型中删除PaymentMethods
并将其移至ViewBag
,这可能会破坏模型绑定。
答案 1 :(得分:1)
//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>
}