我正在构建一个网站,用户可以填写从数据库动态生成的多页表单。我使用JQuery将数据发布到我的控制器并返回表单的下一页。它适用于除文件之外的所有内容。Mvc 4动态表单文件上传
问题是将文件发布到我的控制器,我使用this post的HtmlHelpers生成文件字段的html。
我的模型:
public class QuestionPage
{
public const string Next = "next";
public const string Prev = "prev";
public const string Save = "save";
public int currentID { get; set; }
public bool advanced { get; set; }
public QuestionPageItem[] questions { get; set; }
public int pagenumber { get; set; }
public int? next { get; set; }
public int? prev { get; set; }
public string submitaction { get; set; }
public int? gotoID { get; set; }
public Dictionary<Int32, QuestionPageTitle> titles { get; set; }
}
public class QuestionPageItem
{
public int id { get; set; }
public string question { get; set; }
public string description { get; set; }
public bool required { get; set; }
public QuestionType type { get; set; }
public object answer { get; set; }
public int? enableID { get; set; }
public bool initHidden { get; set; }
public QuestionOptionIndexModel[] options { get; set; }
}
我的静态视图:
using (Html.BeginForm("Form", "QuestionPage", new { id = Model }, FormMethod.Post, new { id = "frm" + Model, name = Model, enctype = "multipart/form-data" }))
{
<div id="formcontainer">
@Html.Partial("_FormPartial", Model)
</div>
}
我的局部视图(_FormPartial)它获取的jQuery AJAX替代,简化了:
@model DPDF.Models.QuestionPage
Some hidden fields...
@for (int i = 0; i < Model.questions.Length; i++)
{
var question = Model.questions[i];
Some hidden fields...
<tr class="@(question.initHidden ? "hidden" : "")" id="@(question.id)" >
show textbox or textarea or radio etc depending on question type, for instance
@Html.TextBox("questions[" + i + "].answer", (question.answer == null ? string.Empty : question.answer.ToString()))
in case of file field
@Html.FileBox("questions[" + i + "].answer")
</tr>
}
的数据获取绑定到问题对象中的答案字段。 我的控制器动作:
[AllowAnonymous]
public ActionResult Form(QuestionPage model)
{
if (!ModelState.IsValid)
return View(model);
// this is to make some hidden fields get the correct new values
ModelState.Clear();
// do stuff to determine what page to show next...
// save data, extract value from model.answer object depending on question type
// make new model and return it
if (Request.IsAjaxRequest())
return PartialView("_FormPartial", model);
return View(model);
}
像文本框普通领域返回类似的String [] { “测试”},文件中的字段返回null。编辑: 也许问题出在JavaScript?这是代码发送到服务器:
var $form = $(form);
var $container = $('#formcontainer');
$container.hide('slide', { direction: direction }, 500, function() {
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: $form.serialize(),
success: function (data, textStatus, jqXHR) {
$container.html(data);
updateOverzicht();
$container.show('slide', { direction: (direction == 'left') ? 'right' : 'left' }, 500);
}
});
});
这项工作将从复选框列表中检索文本框和字符串数组中的字符串吗? – Blight 2013-03-13 15:39:55
@Blight Nope,为此,您必须为每个字段提供'@ Html.HiddenFor(m => Model.questions [i] .FieldName)' – mattytommo 2013-03-13 15:43:35
您能否告诉我如何检索发布的信息由隐藏字段的用户? – Blight 2013-03-13 15:50:32