对于学校作业,我需要使用ASP.NET进行投票 我在尝试在数据库中编写答案时遇到的问题是只有一个问题和一个答案被写入其中。
这是视图
@model CinemaJamV2.WebUIV2.Models.EnqueteModel
@{
ViewBag.Title = "Enquete";
}
<h2>Enquete</h2>
@Html.ValidationSummary(true)
@using (Html.BeginForm("Enquete", "Enquete", new { vraag = "vraag", antwoord = "antwoord", naam = "naam", cijfer = "cijfer" }))
{
<div class="col-md-12">
@for(var i=0;i< Model.enquetevragen.Count();i++)
{
<div class="thumbnail">
@Html.LabelFor(model => model.enquetevragen[i].vraag, new { htmlAttributes = new { @class = "form-control" } })
@Html.EditorFor(model => model.enquete.antwoord, new { htmlAttributes = new { @class = "form-control" } })
@Html.EditorFor(model => model.enquete.cijfer, new { htmlAttributes = new { @class = "form-control" } })
</div>
}
</div>
<div class="col-md-12">
<p>Naam <input type="text" name="naam" /> </p>
<input type="submit" name="submit" value="Verzend" />
</div>
}
这是控制器:
namespace CinemaJamV2.WebUIV2.Controllers
{
public class EnqueteController : Controller
{
private IRepository<Enquete> repository;
private IRepository<EnqueteVraag> a_repository;
private CineJamContext db = new CineJamContext();
public EnqueteController(IRepository<Enquete> a_model, IRepository<EnqueteVraag> vraag_model)
{
repository = a_model;
a_repository = vraag_model;
}
[HttpGet]
public ActionResult Enquete()
{
EnqueteModel enquetevragen = new EnqueteModel
{
enquetevragen = a_repository.List
};
return View(enquetevragen);
}
[HttpPost]
public ActionResult Enquete(Enquete enquete)
{
if (ModelState.IsValid)
{
db.Enquetes.Add(enquete);
db.SaveChanges();
return RedirectToAction("Enquete");
}
return View(enquete);
}
}
}
ModelView:
namespace CinemaJamV2.WebUIV2.Models
{
public class EnqueteModel
{
public List<Enquete> enquetes {get; set;}
public Enquete enquete { get; set; }
public List<EnqueteVraag> enquetevragen { get; set; }
}
}
这是Model Enquete,它应该包含所有给定的答案:
namespace CinemaJamV2.Domain.Entities
{
[Table("Enquete")]
public partial class Enquete : IEntity
{
public int Id { get; set; }
[StringLength(1000)]
public string vraag { get; set; }
[StringLength(1000)]
//[Required]
public string antwoord { get; set; }
public int? cijfer {get; set;}
[StringLength(50)]
//[Required]
public string naam { get; set; }
}
}
此模型包含所有问题
namespace CinemaJamV2.Domain.Entities
{
[Table("EnqueteVraag")]
public partial class EnqueteVraag : IEntity
{
public int Id { get; set; }
[StringLength(1000)]
public string vraag { get; set; }
}
}
答案 0 :(得分:0)
POST
的操作只有一个Model的实例作为参数。您需要阅读:Model binding to a list
答案 1 :(得分:0)
你需要使用具有Enquete列表的视图模型,然后再次使用post方法进行循环并将其保存到数据库。
请参阅以下链接了解样本。
http://www.binaryintellect.net/articles/b1e0b153-47f4-4b29-8583-958aa22d9284.aspx
http://www.c-sharpcorner.com/UploadFile/pmfawas/Asp-Net-mvc-how-to-post-a-collection/
http://www.codeproject.com/Tips/855577/List-of-Model-Object-Post-to-Controller-in-ASP-NET