我剛剛完成完全相同的任務。
我選擇爲我的動態表單對象編寫自定義模型聯編程序。模型活頁夾爲隱藏字段提取了一堆前綴表單鍵,其中包含一些關於該問題的分隔元數據(即IsRequired,QuestionType,QuestionId等)
我正在使用MVC3,但我認爲這應該都適用於MVC2。
我創建了一個模型綁定器,如:
public class DynamicFormModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
// Create the object to be bound to (I had a kind of form object
// with a simple list of answer objects
DynamicForm form = new DynamicForm(new List<Answer>());
HttpRequestBase request = controllerContext.HttpContext.Request;
var keys = request.Form.AllKeys.Where(k => k.StartsWith("MyFormsKeyPrefix_Meta_"));
foreach (var key in keys)
{
// Loop over each question's meta data. Metadata will always be present
// even if the user hasn't selected an answer as it's a hidden field
// TODO: Split the meta data and pull out IsRequired, QuestionType etc
// TODO: Get all the posted form values for the question (these values
// will come from textboxes, dropdowns, checkboxes etc)
// Use a prefix like: MyFormsKeyPrefix_Answer_{QuestionId}
// textboxes & dropdowns will only ever have one value
// but checkboxes could have multiple
// TODO: If it's a mandatory question then ensure there is at least
// one posted value that is not an empty string
// If there is a validation error then add it to the model state
bindingContext.ModelState.AddModelError(key, "Field is required");
foreach(var answerHtmlName in answerHtmlNames)
{
// TODO: Loop over each posted answer and create some kind of nice
// Answer object which holds the QuestionId, AnswerId, AnswerOptionId
// and Value etc.
// Add the answer to the forms answers list
form.Answers.Add(answer);
}
}
return form;
}
}
我註冊ModelBinder的全球。ASAX使用下列內容:
ModelBinders.Binders.Add(typeof(DynamicForm), new DynamicFormModelBinder());
所以,這臨危形式後的操作方法如下所示:
public ActionResult ProcessForm(DynamicForm form) {
if(ModelState.IsValid)
{
DynamicFormService.Process(form);
return RedirectToAction("TheHttpGetAction");
}
return TheHttpGetAction();
}
你可以分享一些代碼的任何機會呢?我沒有編寫自定義模型綁定器,因此一個示例會很有幫助。 – SonOfPirate 2011-05-09 17:39:09
我已經更新了答案,試着給出幾個指針。我爲另一家公司編寫了它,並且目前沒有代碼交付,所以我剛剛寫了一些僞代碼和一些註釋 – 2011-05-09 18:22:28
由於某種原因,我在保存編輯時丟失了代碼着色 - 無法工作爲什麼... – 2011-05-09 18:30:21