我有一个5个字符串值的列表(每个问题的可能答案),我想让用户键入。但是当我提交表单时,会出现一个错误:"Collection is read-only“。这里出了什么问题?
这是我的视图模型:
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;
}
}控制器中的我的post方法:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddQuestion(QuestionVM questionVM)
{
try
{
if (ModelState.IsValid)
{
Question question = questionVM.ToQuestion(context);
context.Questions.Add(question);
context.SaveChanges();
return RedirectToAction("Questions");
}
}
catch (DataException /* dex */)
{
//Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Trenutno nije moguće snimiti promjene, pokušajte ponovo.");
}
return View(questionVM);
}视图的一部分:
@Html.EditorFor(model => model.PossibleAnswers, "PossibleAnswers")和模板:
@model IEnumerable<string>
@{
ViewBag.Title = "PossibleAnswers";
}
@foreach (var str in Model)
{
@Html.TextBoxFor(m => str)
}发布于 2015-02-16 05:33:24
请确保您遵循了以下提示:
Views/Shared/EditorTemplates文件夹内添加编辑器模板@models让应用程序检测起来更容易。《[UIHint("TemplateName")]剃须刀。看看aspnet-mvc-display-and-editor-templates吧。
https://stackoverflow.com/questions/28531035
复制相似问题