C# 通过POST将数据传递给控制器方法
我有一个“调查”页面,声明如下:C# 通过POST将数据传递给控制器方法,c#,asp.net-mvc-3,razor,C#,Asp.net Mvc 3,Razor,我有一个“调查”页面,声明如下: @using (Html.BeginForm("Survey", "Home", new { questionList = Model.Questions }, FormMethod.Post)) { <div class="survey"> <ol class="questions"> @foreach (Question q in Model.Questions)
@using (Html.BeginForm("Survey", "Home", new { questionList = Model.Questions }, FormMethod.Post))
{
<div class="survey">
<ol class="questions">
@foreach (Question q in Model.Questions)
{
<li class="question" id="@q.QuestionName">
@q.QuestionText<br />
@foreach (Answer a in q.Answers)
{
<input class="answer" id="@a.DisplayName" type="checkbox" /><label for="@a.DisplayName">@a.AnswerText</label>
if (a.Expandable)
{
<input type="text" id="@a.DisplayNameFreeEntry" maxlength="250" /> <span>(250 characters max)</span>
}
<br />
}
</li>
}
</ol>
</div>
<div class="buttons">
<input type="submit" value="Finish" />
</div>
}
@使用(Html.BeginForm(“调查”、“主页”,新的{questionList=Model.Questions},FormMethod.Post))
{
@foreach(模型中的问题q.问题)
{
@q、 问题文本
@foreach(问题答案中的答案a)
{
@a、 答复文本
如果(a.可扩展)
{
(最多250个字符)
}
}
}
}
当我单步执行代码时,它会点击我为处理他们的调查而设置的方法:
[HttpPost]
public ActionResult Survey( List<Question> questionList, FormCollection postData)
{
//Process Survey
}
[HttpPost]
公共行动结果调查(列表问题列表,FormCollection postData)
{
//过程调查
}
但是,当我逐步执行时,我发现变量questionList
为空,并且变量postData
不包含表单中的任何数据。试图通过请求[a.Displayname
访问复选框也不起作用
我读到的所有内容都表明,这是将值从模型持久化到提交方法的正确方法,并且我应该能够以这种方式访问FormCollection
我做错了什么?您必须将问题列表保存为页面上的一个隐藏字段。非基本类型不会通过简单地传入而持久化 你可以这样做的一个方法是
@Html.HiddenFor(m => m.Foo)
或者你也可以像这样直接用HTML来做
<input type="hidden" name="Var" value="foo">
其中m是您的模型。一个问题是您的复选框和文本框未正确绑定到您的模型
您应该使用
@Html.CheckBoxFor
和@Html.TextBoxFor
事实上postData
是空的,因为表单标记中每个id为的输入元素都应该随POST请求一起传递
但是,questionList
不会以这种方式接收,因为它是一个复杂类的列表(不仅仅是字符串或int),而默认的ModelBinder
(将HTTP请求变量转换为传递给action方法的参数)不支持复杂类的列表
如果您希望能够接收列表,则必须使用CustomModelBinder
实现自己的绑定机制
可以帮助您实现它。我对MVC的显示端非常陌生。如何将问题列表保存为隐藏字段?您可能会看到这个和这个