asp.net mvc 3 Html.GetUnobtrusiveValidationAttributes and nested models
Here is the situation. I have some ViewModels that contain nested complex model types. Here is a snippet of one of the models (this is not a complete class):
/// <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
And a snippet from the ContactModel class (not complete):
#region Company
[Required(AllowEmptyStrings = false)]
[StringLength(128)]
public string Company { get; set; }
#endregion
My issue is that I need to be able to obtain the validation attributes from the nested model type, ContactModel, for client-side validation. I use the manual approach in most views because I don't use the *For() helper methods. Here is what I do:
@Html.TextBox(
_titleField,
Model.Contact.Title,
new Dictionary<string,object>(Html.GetUnobtrusiveValidationAttributes("Company"))
{
{ "class", "CTextBox" },
{ "style", "width:100%;" }
})
This works like a champ and produces the expected validation attributes from the Model, ONLY, wh开发者_高级运维en the Model for the view is the Model that has the "validation" attributes applied. When the Model having the "validation" attributes is within a nested Model object, this does not work. I am struggling trying to figure out how to get the validation attributes for this scenario. The view is complicated, and I cannot decompose it any further into multiple views of models, so I need it working with a nested model.
I have tried numerous approaches, but won't get into them yet in an attempt to get untainted answers. I will say I have tried using my binding prefix as well as going through some of the static "ModelMetadata" classes to drill into my nested model structure, but as of yet no luck. Any help is appreciated.
Let me know what else you need to maybe help.
I have also read a lot of Brad Wilson's blog posts as well as other guys in his realm, but no luck so far.
You must to provide the complete name of the attribute:
(Html.GetUnobtrusiveValidationAttributes("Contact.Company"))
Where "Contact" is the name of the instance
精彩评论