我希望这不是一个多余的问题。我已经阅读了几个问题和答案。我认为我的问题更基本。我一直在尝试使用How can I bind a radio button with model data in ASP.Net MVC?作为我的主要参考...但我目前的错误是:
对象引用未设置为对象的实例。
描述:执行期间发生了未处理的异常 当前的网络请求。请查看堆栈跟踪了解更多信息 有关错误的信息以及它在代码中的起源。
异常详细信息: System.NullReferenceException:对象引用不是 设置为对象的实例。
来源错误: ~~ foreach(Model.ClaimTypeList中的var claimtype)
我的模型(简化):
[Authorize]
public class Claim
{
[Display(Name = "Claim Type :")]
public int ClaimType { get; set; }
public List<ClaimType> ClaimTypeList { get; set; }
}
public class ClaimType
{
public string ID { get; set; }
public string Type { get; set; }
}
我的控制器(简化):
// GET: Claim/Create
public ActionResult Create()
{
return View();
}
// POST: Claim/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
var claim = new Claim
{
//I think the best way to populate this list is to call a service here.
ClaimTypeList = new List<ClaimType>
{
new ClaimType{ID="1" , Type = "SMS"},
new ClaimType{ID="2" , Type = "Phone"},
new ClaimType{ID="3" , Type = "CC"},
new ClaimType{ID="4" , Type = "Mail"}
}
};
return RedirectToAction("Index");
}
catch
{
return View();
}
}
我视图中的单选按钮
@{
foreach (var claimtype in Model.ClaimTypeList)
{
@Html.RadioButtonFor(model => model.ClaimType, new { id = "claimtype" + claimtype.ID })
}
}