Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use EditorForModel and DataAnnotations for complex types in a wrapping ViewModel?
    text
    copied!<p>I have a ViewModel wrapping two complex types:</p> <pre><code>public class EditProductViewModel { public ProductData ProductData { get; set; } public FridgeContent FridgeContent { get; set; } } </code></pre> <p>and this view:</p> <pre><code>@model EditProductViewModel @using (Html.BeginForm("Edit", "ProductData", FormMethod.Post)) { @Html.EditorForModel() [...] } </code></pre> <p>ProductData and FridgeContent contain POCO properties with DataAnnotations like this:</p> <pre><code>public class FridgeContentMetadata : DatabaseEntityMetadataBase { [Required] [HiddenInput(DisplayValue = false)] public int ProductDataId { get; set; } [Required] [UIHint("StringReadOnly")] public int ScaleId { get; set; } [Required] [UIHint("StringReadOnly")] [Range(0.01, float.MaxValue, ErrorMessage = "The weight of a product must be positive.")] public float Weight { get; set; } [...] } </code></pre> <p>I want to edit both ProductData and FridgeContent in the EditProductView using the appropriate data annotations from those classes and the EditorForModel() method (I don't want to generate the templates myself). I therefore created the templates ProductData.cshtml and FridgeContent.cshtml in /Views/Shared/EditorTemplates/:</p> <pre><code>@model FridgeContent @Html.EditorForModel() </code></pre> <p>Unfortunately, the view for EditProductViewModel is empty (no errors raised). If I use EditorForModel for either FridgeContent or ProductData alone, it's working fine. I also tried adding [UIHInt("..")] annotations to EditProductViewModel but that doesn't make a difference. </p> <p>What am I missing?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload