我有一个带有文本框的表单和一些带有单选按钮的问题。我希望此表单的用户检查每个单选按钮。这是强制性的。我想将检查是或否的值与每个问题的名称或 ID 一起使用实体框架写入数据库。
如果我知道如何将此信息收集到集合中,我可以写入数据库。
请问如何将这些添加到集合中?
public class HomeController : Controller
{
public ActionResult Index()
{
}
[HttpPost]
public ActionResult ProcessToDb()
{
return View();
}
}
@using (@Html.BeginForm("ProcessToDb", "Home", FormMethod.Post))
{
<h2>My Test</h2>
<div>Email Address</div>
<div>
@Html.TextBox("EmailAddress", null, new { @class = "form-control" })
</div>
<div>
<label for="question1">Are you ok?</label>
<input type="radio" name="group1" value="Yes">Yes
<input type="radio" name="group1" value="No">No
</div>
<div>
<label for="question2">Is the answer correct?</label>
<input type="radio" name="group2" value="Yes">Yes
<input type="radio" name="group2" value="No">No
</div>
<div>
<label for="question3"> Did you overtake him ?</label>
<input type="radio" name="group3" value="Yes">Yes
<input type="radio" name="group3" value="No">No
</div>
<div>
<input type="submit" value="Send"> <input type="reset">
</div>
}
例如,您需要从代表您想要显示/编辑的内容的视图模型开始
public class AnswerVM
{
public int QuestionID { get; set; }
public string QuestionText { get; set; }
public bool Answer { get; set; }
}
然后在GET方法中
public ActionResult Index()
{
List<AnswerVM> model = new AnswerVM();
// populate the collection from the database but for testing purposes
model.Add(new AnswerVM() { QuestionID = 1, QuestionText = "Are you ok?" });
model.Add(new AnswerVM() { QuestionID = 2, QuestionText = "Is the answer correct?" });
return View(model);
}
然后在视图中
@model List<yourAssembly.AnswerVM>
@using (Html.BeginForm())
{
for(int i = 0; i < Model.Count; i++)
{
@Html.HiddenFor(m => m[i].QuestionID)
@Html.DisplayFor(m => m[i].QuestionText)
<label>
@Html.RadioButtonFor(m => m[i].Answer, true)
<span>Yes</span>
</label>
<label>
@Html.RadioButtonFor(m => m[i].Answer, false)
<span>No</span>
</label>
}
<input type="submit" />
}
以及 POST 方法
public ActionResult Index(List<AnswerVM> model)
{
foreach (AnswerVM answer in model)
{
// access the QuestionID and Answer properties and save to the database
}
// redirect
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)