mvc:将选中的单选按钮值添加到集合中并保存到数据库

时间:2015-06-30 01:33:12

标签: asp.net-mvc-4

我有一个带有文本框的表单和一些带有单选按钮的问题。我希望这个表单的用户检查每个单选按钮。这是强制性的。我想检查值是否为是或否以及每个问题的名称或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>
        }

1 个答案:

答案 0 :(得分:2)

您需要从表示要显示/编辑内容的视图模型开始,例如

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
}