Validations not show up using EF Code First with complex types

前端 未结 2 1093
梦谈多话
梦谈多话 2021-01-29 05:08

This is a continuation of this question Model class and Mapping

I had my Client class now working fine and it\'s defined as

using System;

using System.         


        
相关标签:
2条回答
  • 2021-01-29 05:31

    After some trials and error I found that the TextBox EditorFor view was the culprit. I documented what I found in my answer here http://forums.asp.net/t/1855963.aspx/1?Validation+messages+don+t+show+up+what+is+missing+

    Basically, as long as I use this EditorFor

    @*@using WebDemo.Helper*@
    @model CardNumbers.Objects.PhoneInfo
    
    <div id="PhoneInfo">
        <div class="float-left">
            @* @Html.EditorFor(model => model.Phone, EditorTemplate.TextBox)*@
            <div class="editor-label">
                @Html.LabelFor(model => model.Phone)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Phone)
                @Html.ValidationMessageFor(model => model.Phone)
            </div>
        </div>
        <div class="float-right">
            @*@Html.EditorFor(model => model.Ext, EditorTemplate.TextBox)*@
            <div class="editor-label">
                @Html.LabelFor(model => model.Ext)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Ext)
                @Html.ValidationMessageFor(model => model.Ext)
            </div>
        </div>
    </div>
    

    All seems to work OK. But if I try to switch to a shorter syntax and use this EditorFor for the textbox:

    <div class="editor-label">
        @Html.Label((ViewData.ModelMetadata.DisplayName??ViewData.ModelMetadata.PropertyName),
            new Dictionary<string, object>
                {
                    { "for", ViewData.ModelMetadata.PropertyName }
                })
    </div>
    <div class="editor-field">
        @Html.TextBox("", (object)Model,
            new Dictionary<string, object>
                {
                    { "id", ViewData.ModelMetadata.PropertyName },
                    { "name", ViewData.ModelMetadata.PropertyName },
                    { "class", "text-box single-line"},
                    { "data-bind", "value: " + ViewData.ModelMetadata.PropertyName },
                })
        @Html.ValidationMessage(ViewData.ModelMetadata.PropertyName,
            new Dictionary<string, object>
                {
                    { "data-valmsg-for", ViewData.ModelMetadata.PropertyName }
                })
    </div>
    

    Validation messages do not show anymore.

    Hopefully this answer will help someone or you may see what I am missing here.

    0 讨论(0)
  • 2021-01-29 05:38

    I don't see a form anywhere on your page. A form context is required for validation to work. You need to wrap the Editor attributes in BeginForm block.

    0 讨论(0)
提交回复
热议问题