MVC动态视图数据和动态视图

时间:2012-05-31 16:56:14

标签: asp.net-mvc asp.net-mvc-3 dynamic views viewmodel

传统上,我使用带有Data Annotations属性的视图模型构建了MVC应用程序,并使用编辑器模板动态呈现视图。一切都很好,它确实减少了构建新视图所需的时间。我的要求最近发生了变化。现在,我无法在设计时定义视图模型。将在视图上呈现的属性在运行时根据业务规则确定。此外,这些属性的验证规则也可以在运行时决定。 (根据业务规则,在我的视图中可能需要我的域模型中不需要的字段)。此外,直到运行时才会知道将呈现的属性集 - 用户A可以从模型编辑6个属性,而用户B可以编辑9个属性。

我想知道是否有可能创建一个模型元数据提供程序,它将从非类型化视图模型的业务规则提供我自己的元数据,如属性名称和值的集合。有人解决了这个问题吗?

2 个答案:

答案 0 :(得分:6)

我通过创建更复杂的模型解决了类似的问题,并使用自定义编辑器模板使模型呈现为典型的编辑器,但使用动态字段信息:

public class SingleRowFieldAnswerForm
{
    /// <summary>
    /// The fields answers to display.
    /// This is a collection because we ask the MVC to bind parameters to it,
    /// and it could cause issues if the underlying objects were being recreated
    /// each time it got iterated over.
    /// </summary>
    public ICollection<IFieldAnswerModel> FieldAnswers { get; set; } 
}

public interface IFieldAnswerModel
{
    int FieldId { get; set; }

    string FieldTitle { get; set; }

    bool DisplayAsInput { get; }

    bool IsRequired { get; }

    bool HideSurroundingHtml { get; }
}

// sample implementation of IFieldAnswerModel
public class TextAreaFieldAnswer : FieldAnswerModelBase<TextAreaDisplayerOptions>
{
    public string Answer { get; set; }
}

EditorTemplates / SingleRowFieldAnswerForm.cshtml:

@helper DisplayerOrEditor(IFieldAnswerModel answer)
{
    var templateName = "FieldAnswers/" + answer.GetType().Name;
    var htmlFieldName = string.Format("Answers[{0}]", answer.FieldId);

    if (answer.DisplayAsInput)
    {
        @Html.EditorFor(m => answer, templateName, htmlFieldName)
        // This will display validation messages that apply to the entire answer. 
        // This typically means that the input got past client-side validation and
        // was caught on the server instead.
        // Each answer's view must also produce a validation message for
        // its individual properties if you want client-side validation to be
        // enabled.
        @Html.ValidationMessage(htmlFieldName)
    }
    else
    {
        @Html.DisplayFor(m => answer, templateName, htmlFieldName)
    }
}
<div class="form-section">
    <table class="form-table">
        <tbody>
            @{
                foreach (var answer in Model.FieldAnswers)
                {
                    if (answer.HideSurroundingHtml)
                    {
                        @DisplayerOrEditor(answer)
                    }
                    else
                    {
                        var labelClass = answer.IsRequired ? "form-label required" : "form-label";
                        <tr>
                            <td class="@labelClass">
                                @answer.FieldTitle:
                            </td>
                            <td class="form-field">
                                <div>
                                    @DisplayerOrEditor(answer)
                                </div>
                            </td>
                        </tr>
                    }
                }
            }
        </tbody>
    </table>
</div>

所以我用SingleRowFieldAnswerForm填充了一系列答案模型。每个答案模型类型都有自己的编辑器模板,允许我自定义应该如何显示不同类型的动态“属性”。例如:

// EditorTemplates/FieldAnswers/TextAreaFieldAnswer.cshtml

@model TextAreaFieldAnswer

@{
    var htmlAttributes = Html.GetUnobtrusiveValidationAttributes("Answer", ViewData.ModelMetadata);
    // add custom classes that you want to apply to your inputs.
    htmlAttributes.Add("class", "multi-line input-field");
}
@Html.TextAreaFor(m => m.Answer, Model.Options.Rows, 0, htmlAttributes)
@Html.ValidationMessage("Answer")

下一个棘手的部分是,当您将此信息发送到服务器时,它本身并不知道要构造哪种类型的IFieldAnswerModel,因此您不能只将SingleRowAnswerForm绑定到您的服务器中参数列表。相反,你必须做这样的事情:

public ActionResult SaveForm(int formId)
{
    SingleRowAnswerForm form = GetForm(formId);
    foreach (var fieldAnswerModel in form.FieldAnswers.Where(a => a.DisplayAsInput))
    {
        // Updating this as a dynamic makes sure all the properties are bound regardless
        // of the runtime type (since UpdateModel relies on the generic type normally).
        this.TryUpdateModel((dynamic) fieldAnswerModel, 
            string.Format("Answers[{1}]", fieldAnswerModel.FieldId));
        }
    ...

由于您为MVC提供了要绑定的每个动态“属性”值,因此它可以毫无困难地绑定每个答案类型的每个属性。

显然我已经省略了很多细节,比如首先如何制作答案模型,但希望这能让你走上正轨。

答案 1 :(得分:1)

您可以在ViewModel,View和Controller中使用ViewData属性,它是动态的,因此可以在运行时解析。