我有一个5个字符串值的列表(每个问题的可能答案),我希望用户输入。但是当我提交表单时出现错误:" Collection是只读的#34;。这有什么不对?
这是我的观点模型:
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;
}
}
我在控制器中的帖子方法:
[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)
}
答案 0 :(得分:0)
确保您已遵循以下提示:
Views/Shared/EditorTemplates
文件夹@models
以便更轻松地检测。 [UIHint("TemplateName")]
引导剃刀。