MVC3 EditorFor动态属性(或需要的解决方法)

Mic*_*ich 4 dynamic editorfor asp.net-mvc-3

我正在构建一个系统,提出问题并收到答案.每个问题都可以有一个自己类型的aswer.让我们把它限制在StringDateTime现在.在Domain中,问题以下列方式表示:

public class Question
{
    public int Id
    {
        get;
        set;
    }

    public string Caption
    {
        get;
        set;
    }

    public AnswerType
    {
        get;
        set;
    }
}
Run Code Online (Sandbox Code Playgroud)

,这里AnswerType

enum AnswerType
{
    String,
    DateTime
}
Run Code Online (Sandbox Code Playgroud)

请注意,实际上我有更多的答案类型.

我提出了创建MVC模型的想法,从Question派生并向其添加Answer属性.所以它必须是这样的:

public class QuestionWithAnswer<TAnswer> : Question
{
    public TAnswer Answer
    {
        get;
        set;
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里开始出现问题.我希望有一个通用的视图来绘制任何问题,所以它需要是这样的:

@model QuestionWithAnswer<dynamic>

<span>@Model.Caption</span>
@Html.EditorFor(m => m.Answer)
Run Code Online (Sandbox Code Playgroud)

因为String我想在这里有简单的输入,因为DateTime我将定义自己的视图.我可以从控制器传递具体模型.但问题是在渲染阶段,当然,它无法确定答案的类型,特别是如果它最初null(默认为String),所以EditorFor不为String其中的所有属性绘制和输入DateTime.

我确实理解问题的本质,但有没有优雅的解决方法?或者我必须实现自己的逻辑来选择基于控件类型的编辑器视图名称(大丑switch)?

Dar*_*rov 5

我个人不喜欢这个:

enum AnswerType
{
    String,
    DateTime
}
Run Code Online (Sandbox Code Playgroud)

我更喜欢使用.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; }
}
Run Code Online (Sandbox Code Playgroud)

然后一个控制器:

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
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

那么主要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" />
}
Run Code Online (Sandbox Code Playgroud)

现在我们可以为我们的答案编辑模板:

~/Views/Home/EditorTemplates/StringAnswer.cshtml:

@model StringAnswer

<div>It's a string answer</div>
@Html.EditorFor(x => x.Value)
@Html.ValidationMessageFor(x => x.Value)
Run Code Online (Sandbox Code Playgroud)

~/Views/Home/EditorTemplates/DateAnswer.cshtml:

@model DateAnswer

<div>It's a date answer</div>
@Html.EditorFor(x => x.Value)
@Html.ValidationMessageFor(x => x.Value)
Run Code Online (Sandbox Code Playgroud)

最后一块是我们答案的自定义模型绑定器:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

将在以下地址注册Application_Start:

ModelBinders.Binders.Add(typeof(AnswerViewModel), new AnswerModelBinder());
Run Code Online (Sandbox Code Playgroud)