简体   繁体   中英

Validating a model in ASP.Net MVC2

I have the following database table:

替代文字

And here is the code I use to validate the model created by Entity Framework:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace UTEPSA.Models
{
    [MetadataType(typeof(Area_Validation))]
    public partial class Area
    {

    }

    public class Area_Validation
    {
        [Required(ErrorMessage = "Campo requerido: Debe elegir un Jefe valido.")]        
        public int IDJefe { get; set; }

        [Required(ErrorMessage = "Campo requerido: Nombre")]
        public string Nombre { get; set; }
    }
}

The ID field is in the int primary key, and it is an identity so it autoincrements and I don't have to ever enter a field.

However, when I try to save the form for it on edit, I NEED to write in any number at all for it to pass.

When I leave the field blank:
Validation fails.

When I type in a string:
Validation fails.

When I type in ANY number:
Validation passes.

Any suggestion on how to ignore this field?

Rendered HTML is:

<form action="/area/create" method="post"> 

        <fieldset> 
            <legend>Fields</legend> 

            <div class="editor-label"> 
                <label for="ID">ID</label> 
            </div> 
            <div class="editor-field"> 
                <input id="ID" name="ID" type="text" value="0" /> 

            </div> 

            <div class="editor-label"> 
                <label for="IDJefe">IDJefe</label> 
            </div> 
            <div class="editor-field"> 
                <input id="IDJefe" name="IDJefe" type="text" value="" /> 

            </div> 

            <div class="editor-label"> 
                <label for="Nombre">Nombre</label> 
            </div> 
            <div class="editor-field"> 
                <input id="Nombre" name="Nombre" type="text" value="" /> 

            </div> 

            <p> 
                <input type="submit" value="Create" /> 
            </p> 
        </fieldset> 

    </form>

然后,您不应将其设置为Required,因为插入时不需要它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM