Asp.net mvc 回发表单时出错:“集合为只读”
我有一个5个字符串值的列表,我希望用户输入每个问题的可能答案。但当我提交表单时,会出现一个错误:集合是只读的。这里怎么了 以下是我的视图模型:Asp.net mvc 回发表单时出错:“集合为只读”,asp.net-mvc,razor,Asp.net Mvc,Razor,我有一个5个字符串值的列表,我希望用户输入每个问题的可能答案。但当我提交表单时,会出现一个错误:集合是只读的。这里怎么了 以下是我的视图模型: public class QuestionVM { public QuestionVM() { PossibleAnswers = new string[5]; } public QuestionVM(Question question) : this() {
public class QuestionVM
{
public QuestionVM() {
PossibleAnswers = new string[5];
}
public QuestionVM(Question question) : this()
{
ID = question.ID;
Text = question.Text;
IsAssociatedWithProfessor = question.IsAssociatedWithProfessor;
IsAssociatedWithAssistant = question.IsAssociatedWithAssistant;
}
public int? ID { get; set; }
public string Text { get; set; }
public bool IsAssociatedWithProfessor { get; set; }
public bool IsAssociatedWithAssistant { get; set; }
public IEnumerable<string> PossibleAnswers { get; set; }
public Question ToQuestion(ApplicationDbContext context)
{
Question question = new Question
{
Text = this.Text,
IsAssociatedWithProfessor = this.IsAssociatedWithProfessor,
IsAssociatedWithAssistant = this.IsAssociatedWithAssistant
};
//ID will be null if creating new question
if(ID != null)
{
question.ID = (int) ID;
}
foreach (string possibleAnswer in this.PossibleAnswersVM.PossibleAnswers)
{
if (!String.IsNullOrEmpty(possibleAnswer))
{
PossibleAnswer existingPossibleAnswer = context.PossibleAnswers.SingleOrDefault(ans => ans.Text == possibleAnswer);
if (existingPossibleAnswer == null)
{
PossibleAnswer ans = new PossibleAnswer { Text = possibleAnswer };
context.PossibleAnswers.Add(ans);
question.PossibleAnswers.Add(ans);
}
else
{
question.PossibleAnswers.Add(existingPossibleAnswer);
}
}
}
return question;
}
}
部分意见:
@Html.EditorFor(model => model.PossibleAnswers, "PossibleAnswers")
和模板:
@model IEnumerable<string>
@{
ViewBag.Title = "PossibleAnswers";
}
@foreach (var str in Model)
{
@Html.TextBoxFor(m => str)
}
确保您遵循了以下提示: 只需在Views/Shared/EditorTemplates文件夹中添加编辑器模板 通过为应用程序定义合适的@models来使用参数化模板,以便更容易地检测。 在需要时使用[UIHintTemplateName]引导剃须刀。
看一看。你有错误吗?我没有。当我运行应用程序时,编辑字段不会出现。您的编辑是否修复了它,还是仍然存在问题?我将以下内容添加到我的问题视图模型中:public QuestionVM{PossibleAnswers=new string[5];},因为我希望用户输入5个输入。它以前没有呈现,因为我的列表是空的。但现在还有另一个问题,当我提交表单时,会出现一个错误:集合只读。完整的错误堆栈跟踪可能会有所帮助。
@model IEnumerable<string>
@{
ViewBag.Title = "PossibleAnswers";
}
@foreach (var str in Model)
{
@Html.TextBoxFor(m => str)
}