我正试图在我的视图中第一次写入模型:第一次写入模型时,我得到ArgumentOutOfRangeException
。
首次写入数组时出错:
private IAdditionalQuestionsService _service;
private SelectedAdditionalQuestionAnswerModel _model;
private void InitializeController()
{
_service = GetObject<IAdditionalQuestionsService>();
//GetPageHeaderText(inst);
ViewBag.GetPageTitle = "Additional Questions";
}
[HttpGet]
public virtual ActionResult Edit()
{
Institution inst = _service.GetInstitution(State.GetInstitutionRecordId());
_model = GetObject<SelectedAdditionalQuestionAnswerModel>();
_model.AddQuestAnswModel = new List<AdditionalQuestionAnswerModel>();
GetPageConfiguration1(inst);
return View(_model);
}
AdditionalQuestionAnswerModel m = GetObject<AdditionalQuestionAnswerModel>();
int c = 0;
foreach (var x in inst.AdditionalQuestions)
{
foreach (var y in x.AdditionalQuestionAnswers)
{
// Error is happening on next line *************
_model.AddQuestAnswModel[c].QuestionText = x.QuestionText;
_model.AddQuestAnswModel[c].InstitutionId = x.InstitutionId;
_model.AddQuestAnswModel[c].AdditionalQuestionId = x.Id;
_model.AddQuestAnswModel[c].AnswerText = y.AnswerText;
_model.AddQuestAnswModel[c].IsSelected = false;
c++;
}
}
答案 0 :(得分:2)
您无法使用_model.AddQuestAnswModel[c]
,因为您从未在列表中添加任何项目。
而不是那样,创建一个新对象并设置其值,然后将该项添加到列表中。
这样的事情:
AdditionalQuestionAnswerModel newItem = new AdditionalQuestionAnswerModel();
//set the values here to newItem
_model.AddQuestAnswModel.Add(newItem);
答案 1 :(得分:2)
您首先要实例化您的列表
_model.AddQuestAnswModel = new List<AdditionalQuestionAnswerModel>();
然后你尝试访问第一个元素
_model.AddQuestAnswModel[c] // c == 0
不向列表中添加任何元素。
在尝试按索引访问列表之前添加元素,或者更简单:
foreach (var y in x.AdditionalQuestionAnswers)
{
AdditionalQuestionAnswerModel newObj = new AdditionalQuestionAnswerModel
{
QuestionText = x.QuestionText;
InstitutionId = x.InstitutionId;
AdditionalQuestionId = x.Id;
AnswerText = y.AnswerText;
IsSelected = false;
};
_model.AddQuestAnswModel.Add(newObj);
}
答案 2 :(得分:0)
Ir表示您_model.AddQuestAnswModel
处的指定邮件中没有任何项目,并且从您的代码中,我发现_model.AddQuestAnswModel
只能使用new List<AdditionalQuestionAnswerModel>()
启动,因此它不包含项目(除非你在构造函数中这样做)。
你需要像这样填写:
_model.AddQuestAnswModel.Add(item);