ASP.NET MVC发送列表以查看编辑项目并将其发送回控制器

时间:2017-12-08 07:09:18

标签: c# asp.net-mvc

我正在为一些调查问题制作一个ASP.NET / MVC应用程序。我创建了一个包含questionid,questiontext和answertext的viewmodel。 在控制器中,我创建了这些viewmodel的列表并填写了questionid和questiontext。 我将列表作为模型发送到视图。所有问题都会显示给用户。 在用户填写问题的答案之后,我希望将列表发送回控制器。但是列表总是空的。

这是我的控制器中的代码:

public class EnqueteController : Controller
{
    private BootCampEval.Models.DB_A2A0BC_bcenqEntities db = new Models.DB_A2A0BC_bcenqEntities();

    // GET: Enquete
    [Authorize]
    public ActionResult CreateEnquete(int enqid = 1)
    {
        List<VMQuestion> questions = new List<VMQuestion>();
        foreach (var q in db.GetQuestionsForEnquete(enqid))
        {
            var viewmodel = new VMQuestion();
            viewmodel.EnqueteTitle = q.EnqTitle;
            viewmodel.EnqueteDate = q.EnqDate;
            viewmodel.QuestionID = q.QuestionID;
            viewmodel.Question = q.Question;
            viewmodel.Answer = "";
            questions.Add(viewmodel);
        }
        return View(questions);
    }


    [Authorize]
    [HttpPost]
    public ActionResult HandleEnquete(List<VMQuestion> answers)
    {
        foreach (var a in answers)
        {
            var answer = new Answers();
            answer.QuestionID = a.QuestionID;
            answer.UserID = User.Identity.GetUserId();
            answer.Answer = a.Answer;
            db.Answers.Add(answer);
        }

        return View();
    }

    public ActionResult Index()
    {
        return View();
    }
}

这是我的观点:

@model IEnumerable<BootCampEval.ViewModels.VMQuestion>
@{
    ViewBag.Title = "CreateEnquete";
    int qnr = 1;

}

<h2>Enquete</h2>
@using (Html.BeginForm("HandleEnquete", "Enquete", FormMethod.Post))
{
    <table>
        @foreach (var q in Model)
        {
            <tr>
                <td>
                    <h3>@qnr. @Html.DisplayFor(modelItem => q.Question)</h3>
                </td>

            </tr>
            <tr>
                <td>
                    @Html.TextAreaFor(itemModel => q.Answer, new { @class = "form-control", style = "min-width: 100%", @id = "Q" + @qnr })
                </td>
            </tr>
            { qnr++; }
        }

    </table>

    <h2 style="text-align:center">Dank voor het invullen en je inzet!</h2>
    <input type="submit" value="Insturen" class="btn btn-block" />
}

0 个答案:

没有答案