我个人不喜欢这样:
enum AnswerType
{
String,
DateTime
}
我更喜欢使用 .NET 类型系统。让我建议你另一种设计。与往常一样,我们从定义视图模型开始:
public abstract class AnswerViewModel
{
public string Type
{
get { return GetType().FullName; }
}
}
public class StringAnswer : AnswerViewModel
{
[Required]
public string Value { get; set; }
}
public class DateAnswer : AnswerViewModel
{
[Required]
public DateTime? Value { get; set; }
}
public class QuestionViewModel
{
public int Id { get; set; }
public string Caption { get; set; }
public AnswerViewModel Answer { get; set; }
}
然后是控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new[]
{
new QuestionViewModel
{
Id = 1,
Caption = "What is your favorite color?",
Answer = new StringAnswer()
},
new QuestionViewModel
{
Id = 1,
Caption = "What is your birth date?",
Answer = new DateAnswer()
},
};
return View(model);
}
[HttpPost]
public ActionResult Index(IEnumerable<QuestionViewModel> questions)
{
// process the answers. Thanks to our custom model binder
// (see below) here you will get the model properly populated
...
}
}
然后是主Index.cshtml
视图:
@model QuestionViewModel[]
@using (Html.BeginForm())
{
<ul>
@for (int i = 0; i < Model.Length; i++)
{
@Html.HiddenFor(x => x[i].Answer.Type)
@Html.HiddenFor(x => x[i].Id)
<li>
@Html.DisplayFor(x => x[i].Caption)
@Html.EditorFor(x => x[i].Answer)
</li>
}
</ul>
<input type="submit" value="OK" />
}
现在我们可以为我们的答案提供编辑器模板:
~/Views/Home/EditorTemplates/StringAnswer.cshtml
:
@model StringAnswer
<div>It's a string answer</div>
@Html.EditorFor(x => x.Value)
@Html.ValidationMessageFor(x => x.Value)
~/Views/Home/EditorTemplates/DateAnswer.cshtml
:
@model DateAnswer
<div>It's a date answer</div>
@Html.EditorFor(x => x.Value)
@Html.ValidationMessageFor(x => x.Value)
最后一块是我们答案的自定义模型活页夹:
public class AnswerModelBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
var typeValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".Type");
var type = Type.GetType(typeValue.AttemptedValue, true);
var model = Activator.CreateInstance(type);
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, type);
return model;
}
}
将在以下位置注册Application_Start
:
ModelBinders.Binders.Add(typeof(AnswerViewModel), new AnswerModelBinder());