我正在构建一个站点,用户可以在其中填写从数据库动态生成的多页表单。我使用 JQuery 将数据发布到我的控制器并返回表单的下一页。它适用于除文件之外的所有内容。
问题是将文件发布到我的控制器,我正在使用这篇文章中的 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[]{"test"} 的内容,文件字段返回 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);
}
});
});