views:

50

answers:

2

I have the following database table:

alt text

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>
A: 

Do you have a hiddenfield <input type="hidden"/> on the form with the ID of the record?

The ID should not be of type="text" it should be type="hidden" if the view is strongly typed then it will assign the correct value of ID from the model supplied to the view, but that is only if (1) the view is strongly typed to the model and (2) you are retrieving the record from the DB...

Alexander
No, see edit for actual HTML that's rendered.
Sergio Tapia
Also remove the hard coded `0` in the `ID` field
Alexander
A: 

You shouldn't set it to Required then, since it's not required for insert.

Yngve B. Nilsen