我有一份表格..基本上是一份包含18个问题的问卷。
它们都是单选按钮组(选择1到5)。
将选定的单选按钮从组中取出的最简单方法是什么(每个按钮组都设置了相同的名称属性)。
它没有强类型..我只是不确定我如何访问控制器中的值?
答案 0 :(得分:1)
在您的HttpPost操作中,您可以接受“FormCollection”类型作为参数。它将包含您要查找的所有数据。
答案 1 :(得分:1)
不是强类型。
这是你最大的问题。所以强烈地输入它......
...当然是一个视图模型:
public class AnswerViewModel
{
public string Label { get; set; }
public string Value { get; set; }
}
public class QuestionViewModel
{
public string Title { get; set; }
public string Answer { get; set; }
public IEnumerable<string> PossibleAnswers { get; set; }
}
然后写一个控制器,负责显示问卷表格并处理该表格的结果:
public class HomeController : Controller
{
public ActionResult Index()
{
// TODO: those are obviously going to come from some data store
// or whatever comes to your mind
var model = new[]
{
new QuestionViewModel
{
Title = "Question 1",
PossibleAnswers = new[]
{
"Answer 1 to question 1",
"Answer 2 to question 1"
}
},
new QuestionViewModel
{
Title = "Question 2",
PossibleAnswers = new[]
{
"Answer 1 to question 2",
"Answer 2 to question 2",
"Answer 3 to question 2",
}
},
};
return View(model);
}
[HttpPost]
public ActionResult Index(IEnumerable<QuestionViewModel> questions)
{
// TODO : Process the answers. Here for each element of the
// questions collection you could use the Answer property
// in order to fetch the answer from the user.
return Content("Thqnks for submitting the questionnaire", "text/plain");
}
}
然后让我们转到视图(~/Views/Home/Index.cshtml
):
@model IEnumerable<QuestionViewModel>
@using (Html.BeginForm())
{
<div>
@Html.EditorForModel()
</div>
<input type="submit" value="submit answers" />
}
最后是为我们的模型集合的每个元素(~/Views/Home/EditorTemplates/QuestionViewModel.cshtml
)呈现的问题的编辑器模板:
@model QuestionViewModel
<h2>@Model.Title</h2>
@Html.HiddenFor(x => x.Title)
@foreach (var item in Model.PossibleAnswers)
{
@Html.RadioButtonFor(x => x.Answer, item)
@item
}
答案 2 :(得分:0)
您可以通过FormCollection
访问这些内容,其中包含所有已发布的值:
public ActionResult QuestionnaireAction(FormCollection formCollection)
{
foreach (var key in formCollection.AllKeys)
{
var value = formCollection[key];
// etc.
}
foreach (var key in formCollection.Keys)
{
var value = formCollection[key.ToString()];
// etc.
}
}
但是,请务必首先阅读帖子How to handle checkboxes in ASP.NET MVC forms?,因为如果您不了解它们的工作方式,则MVC中的复选框可能很奇怪。