我有一个创建视图来添加问题的答案,目前用户只能在他点击提交按钮时同时添加一个答案,而不是我希望用户能够插入多个答案对象进入相同的视图然后系统在用户点击提交按钮后将所有这些新的答案对象添加到数据库,我当前的视图如下所示: -
@model Elearning.Models.Answer
@{
ViewBag.Title = "Create";
}
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<div id = "remove">
@using (Ajax.BeginForm("Create", "Answer", new AjaxOptions
{
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "remove"
}))
{
<div id = "returnedquestion">
@Html.ValidationSummary(true)
<fieldset>
<legend>Answer</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Description)
@Html.ValidationMessageFor(model => model.Description)
</div>
</fieldset>
<input type= "hidden" name = "questionid" value = @ViewBag.questionid>
<input type= "hidden" name = "assessmentid" value = @ViewBag.assessmentid>
<input type="submit" value="Add answer" />
</div>
}
</div>
并且操作方法如下所示: -
public ActionResult Create(int questionid)//, int assessmentid)
{
ViewBag.questionid = questionid;
Answer answer = new Answer();
return PartialView("_answer",answer);
}
//
// POST: /Answer/Create
[HttpPost]
public ActionResult Create(int questionid, Answer a)
{
if (ModelState.IsValid)
{
repository.AddAnswer(a);
repository.Save();
return PartialView("_details",a);
}
return View(a);}
那么我如何修改上面的代码,以便能够在同一个视图中插入多个答案对象,然后在用户点击提交按钮的同时提交这些答案对象? < / p>
答案 0 :(得分:1)
尝试发布一个列表 当用户单击“添加答案”时,通过javascript添加输入。 提交表单时,它会将所有答案数据发布到List
<script>
$(document).ready(function () {
var anwserCount = 1;
$("#addbutton").click(function () {
$("#AnwsersDiv")
.append("<input type='text' name='Anwsers[" + anwserCount + "]'/>");
anwserCount += 1;
});
});
</script>
@using (Html.BeginForm())
{
<div id="AnwsersDiv">
<input type="text" name="Anwsers[0]" />
</div>
<input id="addbutton" type="button" value="Add answer" />
<input type="submit" value="submit" />
}
模型
public class Answer
{
public List<String> Anwsers { get; set; }
}
提交表格时
答案 1 :(得分:1)
我认为这就是你要找的东西
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
结论:您应该使用ICollection<Answer>
参数进行发布操作,然后在发布主表单时轻松获取它们,并创建相应的QUESTION对象,然后保存他们都只有一次提交。