【问题标题】:asp.net mvc 3 Html.GetUnobtrusiveValidationAttributes and nested modelsasp.net mvc 3 Html.GetUnobtrusiveValidationAttributes 和嵌套模型
【发布时间】:2011-03-21 10:46:35
【问题描述】:

情况是这样的。我有一些包含嵌套复杂模型类型的 ViewModel。这是其中一个模型的 sn-p(这不是一个完整的类):

/// <summary>
/// Defines the overall view when viewing contact details.
/// </summary>
public sealed class ContactDetailsViewModel : BaseViewModel
{
    public ContactDetailsViewModel() : base() { }
    public ContactDetailsViewModel(WebSession webSession) : base(webSession) { }
    public ContactDetailsViewModel(WebSession webSession, string returnUrl) : base(webSession, returnUrl) { }

    #region Contact
    /// <summary>
    /// The contact being viewed.
    /// </summary>
    public ContactModel Contact { get; set; }
    #endregion

还有来自 ContactModel 类的 sn-p(不完整):

    #region Company
    [Required(AllowEmptyStrings = false)]
    [StringLength(128)]
    public string Company { get; set; }
    #endregion

我的问题是我需要能够从嵌套模型类型 ContactModel 中获取验证属性以进行客户端验证。我在大多数视图中使用手动方法,因为我不使用 *For() 辅助方法。这是我的工作:

@Html.TextBox(
_titleField,
Model.Contact.Title,
new Dictionary<string,object>(Html.GetUnobtrusiveValidationAttributes("Company"))
{
    { "class", "CTextBox" },
    { "style", "width:100%;" }
})

这就像一个冠军,并从模型中产生预期的验证属性,只有当视图的模型是应用了“验证”属性的模型时。当模型具有“验证”属性在嵌套的模型对象中,这不起作用。我正在努力弄清楚如何获取此场景的验证属性。视图很复杂,我无法将其进一步分解为模型的多个视图,因此我需要它与嵌套模型一起使用。

我已经尝试了许多方法,但还没有深入了解它们以试图获得无污染的答案。我会说我已经尝试使用我的绑定前缀以及通过一些静态“ModelMetadata”类来钻入我的嵌套模型结构,但到目前为止还没有运气。任何帮助表示赞赏。

让我知道您还需要什么帮助。

我还阅读了 Brad Wilson 以及他领域中的其他人的很多博客文章,但到目前为止还没有运气。

【问题讨论】:

    标签: asp.net asp.net-mvc-3 modelmetadata


    【解决方案1】:

    您必须提供属性的完整名称:

    (Html.GetUnobtrusiveValidationAttributes("Contact.Company"))
    

    其中“联系人”是实例的名称

    【讨论】:

    • 谢谢!我没有想到的一件事。哇,谢谢。
    猜你喜欢
    • 2014-08-26
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多