我有一個MVC3剃刀形式。它有一個單選按鈕列表和一些其他文本字段。當我按提交控制器後操作獲取視圖模型,其中所有字段正確佈局,除RegionID。MVC3 RadioButtonFor的值沒有綁定到模型
型號:
namespace SSHS.Models.RecorderModels
{
public class CreateViewModel
{
...
public int RegionID { get; set; }
...
}
}
控制器:
namespace SSHS.Controllers
{
public class RecorderController : Controller
{
...
public ActionResult Create()
{
EntrantDBEntities db = new EntrantDBEntities();
List Regions = new List(db.Region);
List Schools = new List(db.School);
List Settlements = new List(db.settlement);
CreateViewModel newEntr = new CreateViewModel();
ViewBag.Regions = Regions;
ViewBag.Schools = Schools;
ViewBag.Settlements = Settlements;
return View(newEntr);
}
[HttpPost]
public ActionResult Create(CreateViewModel m)
{
EntrantDBEntities db = new EntrantDBEntities();
Entrant e = new Entrant()
{
FatherName = m.FatherName,
Lastname = m.LastName,
LocalAddress = m.LocalAddress,
Name = m.Name,
RegionID = m.RegionID,
PassportID = m.PassportID,
SchoolID = m.SchoolID,
SettlementID = m.SattlementID,
TaxID = m.TaxID,
};
db.Entrant.AddObject(e);
db.SaveChanges();
return RedirectToAction("Index");
}
}
查看:
@model SSHS.Models.RecorderModels.CreateViewModel
@using SSHS.Models
@using (Html.BeginForm("Create", "Recorder", FormMethod.Post))
{
@foreach (Region item in ViewBag.Regions)
{
@Html.RadioButtonFor(m => m.RegionID, item.RegionID)
@Html.Label(item.RegionName) - @item.RegionID
}
...
...
}
的創建(CreateViewModel m)方法通常從所有文本框獲取數據,但RegionID始終爲0.
單選按鈕用於真/假狀態。根據你的情況你可能使用了選擇列表。嘗試在[HttpPost] Create方法中檢查請求[「YourRegionRadioId」],如果它有任何值。 – 2012-09-20 08:21:27
請求[「RegionSelect」]未設置爲對象的實例 – RazorRunner
現在嘗試使用選擇列表 – RazorRunner