problems with ModelState.IsValid does not respect the required

0

I am doing validations to the text fields of a form through a model that I decorate with [Required] to require certain fields but cn the controller when I do the condition if (ModelState.IsValid) does not do the saving in the BD since the model is not valid until all the fields are entered, as I can do so that only the three fields that I use with the required in the model are only the obligatory ones and not the others.

view

    <script>
    $(document).ready(function () {
        $('#Table tbody > tr').remove();
        MuestraTodasLasVariables();
        $('#btnGuarda').click(function () {
            
            var url = "http://localhost:6892/Validador/AgregarVariable";
            var data = new FormData();

            var data = {
                items: {
                    VariableNombre: $('#txtNombreVariable').val()
                    , DatoTipo: $('#DDLTipoDato').val()
                    , NumeroDecimales: $('#txtNumDecimales').val()
                    , ValorConstante: $('#txtValorFijo').val()
                    , ValorMinimo: $('#txtValMinimo').val()
                    , ValorMaximo: $('#txtValMaximo').val()
                    , ValorIncremento: $('#txtIncremento').val()
                    , IdVariableIdentificador: $('#DDLIDVariable').val()
                }
            };

            $.ajax({
                
                type: "Post",
                url: url,
                datatype: "json",
                contentType: 'application/json;charset=utf-8',
                processData: false,
                data: JSON.stringify(data),
                success: function (data) {
                    
                    if (data.Success === true) {
                        $('#Table tbody > tr').remove();
                        MuestraTodasLasVariables();
                        $('#txtNombreVariable').val('');
                        $('#DDLIDVariable').val(0);
                        $("#DDLTipoDato option[value='- Seleccione -']").prop("selected", true);
                        $('#txtNumDecimales').val('');
                        $('#txtValorFijo').val('');
                        $('#txtValMinimo').val('');
                        $('#txtValMaximo').val('');
                        $('#txtIncremento').val('');
                        $('#DDLIDVariable').val(0)

                        //alert("Se ha agregado una variable exitosamente!");
                        //$('.ModalGuardadoVariable').click();
                        messageOK('Aviso', data.Mensaje);
                    }
                    else {
                        //alert("Hubo un error. Intentelo nuevamente");
                        //$('.ModalNoGuardadoVariable').click();
                        messageOK('Aviso', data.Mensaje);
                    }
                    //    alert(data.mensaje);
                },
                error: function (xhr, status, errorthrow) {
                    //alert(xhr.error);
                    //alert("error en proceso");
                }
            });


        });


    });
    function MuestraTodasLasVariables() {
        var url = "http://localhost:6892/Validador/TodasLasVariables";
        $.ajax({
            type: "Post",
            url: url,
            datatype: "json",
            contentType: false,
            processData: false,
            success: function (data) {
                if (data.Success === true) {

                    $.each(data.Variables, function (i, registro) {

                        var trs = $("#Table tr").length;
                        var nuevaFila = "<tr>";

                        nuevaFila += '<td>';
                        nuevaFila += '' + registro.NombreVaribale + '';
                        nuevaFila += '</td >';
                        nuevaFila += '<td>';
                        nuevaFila += '' + registro.TipoDato + '';
                        nuevaFila += '</td >';

                        nuevaFila += "</tr>";
                        $("#Table").append(nuevaFila);

                    });
                    if ($('#Table >tbody >tr').length == 0) {
                        // alert("No hay filas en la tabla!!");
                        $('#TablaMostrarVariables').css('display', 'none');
                        //$("#msgTabla").removeAttr("style", "display:none");
                        $('#MsgTabla').css('display', 'block');
                    } 
                }
            },
            error: function (xhr, status, errorthrow) {
                //alert(xhr.error);
                //alert("error en proceso");
            }

        });
    }
</script>
<div class="col-md-12 text-center">
    <h3>Agregar Variable</h3>
</div>
<div class="row">
    <div class="col-md-4">
        <p>Bienvenido: @ViewBag.Usuario</p>
    </div>
    <div class="col-md-4">
    </div>
    <div class="col-md-4 text-right">
        @Html.ActionLink("Cerrar sesión", "Index", "Home")
    </div>
</div>

<div class="container-fluid">
    <div class="row">
        <div class="text-left col-md-8">
            <div class="container">
                &nbsp;
            </div>
        </div>
        <div class="text-left col-md-4" style="padding-top:10px">
            <div class="text-right">
                @Html.ActionLink("Regresar", "AgregarFormula", "Validador", new { @class = "btn btn-default" })
                <button id="btnGuarda" type="button" class="btn btn-primary">Guardar</button>
            </div>
        </div>
    </div>
    <p></p>
    <div class="panel panel-default">
        <div class="panel-body">

            @*using (Html.BeginForm("AgregarVariable", "Validador", null, FormMethod.Post, new { id = "formulaForm" }))
                {
                    @Html.AntiForgeryToken()
                    @Html.ValidationSummary()*@

            <div class="text-left col-md-4">
                <label class="col-sm-12 control-label" for="email-03">Nombre de la variable:</label>
                @Html.TextBox("txtNombreVariable", null, new { @class = "form-control" })
            </div>
            <div class="text-left col-md-4">
                <label class="col-sm-12 control-label" for="email-03">Identificador de Variable:</label>
                @Html.DropDownList("DDLIDVariable", ViewBag.VariablesIdentificador as SelectList, new { @class = "form-control", id = "DDLIDVariable" })
            </div>
            <div class="text-left col-md-4">
                <label class="col-sm-12 control-label" for="email-03">Tipo de dato:</label>
                @Html.DropDownList("DDLTipoDato", ViewBag.TipoDato as SelectList, new { @class = "form-control", id = "DDLTipoDato" })
            </div>
            <div class="text-left col-md-4">
                <label class="col-sm-12 control-label" for="email-03">No. de decimales:</label>
                @Html.TextBox("txtNumDecimales", null, new { @class = "form-control" })
            </div>
            <div class="text-left col-md-4">
                <label class="col-sm-12 control-label" for="email-03">Valor fijo:</label>
                @Html.TextBox("txtValorFijo", null, new { @class = "form-control" })
            </div>
            <div class="text-left col-md-4">
                <label class="col-sm-12 control-label" for="email-03">Valor minimo:</label>
                @Html.TextBox("txtValMinimo", null, new { @class = "form-control" })
            </div>
            <div class="text-left col-md-4">
                <label class="col-sm-12 control-label" for="email-03">Valor maximo:</label>
                @Html.TextBox("txtValMaximo", null, new { @class = "form-control" })
            </div>
            <div class="text-left col-md-4">
                <label class="col-sm-12 control-label" for="email-03">Incremento:</label>
                @Html.TextBox("txtIncremento", null, new { @class = "form-control" })
            </div>

            <btn id="ModalGuarda" type="button" class="btn btn-default ModalGuardadoVariable" href="#" data-toggle="modal" data-target="#ModalGuardadoVariable" style="display:none;">Abrir ventana de aviso de termino de captura</btn>
            <btn id="ModalAvisaNoGuardo" type="button" class="btn btn-default ModalNoGuardadoVariable" href="#" data-toggle="modal" data-target="#ModalNoGuardadoVariable" style="display:none;">Abrir ventana de aviso de empate</btn>

        </div>
    </div>
   
    <div id="TablaMostrarVariables" style="display:block">
        <hr />
        <table id="Table" class="table table-striped table-condensed">
            <thead>
                <tr>
                    <th class="text-center">Nombre Variable</th>
                    <th class="text-center">Tipo de Dato</th>
                </tr>

            </thead>
            <tbody></tbody>
        </table>
    </div>
    <div id="MsgTabla" style="display:none">
        <div class="alert alert-warning">
            <strong>No hay variables</strong>
        </div>
    </div>
</div>

controller

[HttpPost]        
    public ActionResult AgregarVariable(entVariables items)
    {
        /*Obtener valores de la sección Crear Variable*/
        var VariableNombre = items.VariableNombre;
        var DatoTipo = items.DatoTipo;
        Int16 valorNumeroDecimales = Convert.ToInt16(items.NumeroDecimales);
        Decimal valorFijo = Convert.ToDecimal(items.ValorConstante);
        Decimal valorMinimo = Convert.ToDecimal(items.ValorMinimo);
        Decimal valorMaximo = Convert.ToDecimal(items.ValorMaximo);
        Decimal valorIncremento = Convert.ToDecimal(items.ValorIncremento);
        Int16 valorIdentificadorVariable = Convert.ToInt16(items.IdVariableIdentificador);

        bool success = false;
        if (ModelState.IsValid)
        {
            try
            {
                SqlParameter[] prms = new SqlParameter[9];

                prms[0] = new SqlParameter("@nombreVariable", SqlDbType.VarChar);
                prms[0].Value = VariableNombre;

                prms[1] = new SqlParameter("@tipoDato", SqlDbType.VarChar);
                prms[1].Value = DatoTipo;

                prms[2] = new SqlParameter("@numeroDecimales", SqlDbType.Int);
                prms[2].Value = valorNumeroDecimales;

                prms[3] = new SqlParameter("@valorFijo", SqlDbType.VarChar);
                prms[3].Value = valorFijo;

                prms[4] = new SqlParameter("@valorMinimo", SqlDbType.Decimal);
                prms[4].Value = valorMinimo;

                prms[5] = new SqlParameter("@valorMaximo", SqlDbType.Decimal);
                prms[5].Value = valorMaximo;

                prms[6] = new SqlParameter("@valorIncremento", SqlDbType.Decimal);
                prms[6].Value = valorIncremento;

                prms[7] = new SqlParameter("@valorIdentificadorVariable", SqlDbType.Int);
                prms[7].Value = valorIdentificadorVariable;

                prms[8] = new SqlParameter("@Activo", SqlDbType.Bit);
                prms[8].Value = 1;

                object resultado = DB.EjecutarEscalar("SP_GuardarVariables", prms);

                success = true;
                //return Json(new { Success = success, Mensaje = "OK" });
                return Json(new { Success = success, Mensaje = "Se guardo la variable exitosamente." });
            }
            catch (Exception)
            {
                //return Json(new { Success = success, Mensaje = "hubo un error" });
                return Json(new { Success = success, Mensaje = "Ocurrio una excepción" });
            }
        }
        else
        {
            List<entVariables> lstErrores = new List<entVariables>();

            if (items.VariableNombre == null || items.VariableNombre == "")
            {
                entVariables error1 = new entVariables();
                error1.NombreInput = "txtNombreVariable";
                error1.MensajeError = "El campo nombre es requerido";
                error1.EstilosError = "1px solid #FF0000";

                lstErrores.Add(error1);
            }
            else
            {
                entVariables error1 = new entVariables();
                error1.NombreInput = "txtNombreVariable";
                error1.MensajeError = "";
                error1.EstilosError = "1px solid #ccc";

                lstErrores.Add(error1);
            }

            if (items.IdVariableIdentificador == 0)
            {
                entVariables error1 = new entVariables();
                error1.NombreInput = "DDLIDVariable";
                error1.MensajeError = "El campo nombre es requerido";
                error1.EstilosError = "1px solid #FF0000";

                lstErrores.Add(error1);
            }
            else
            {
                entVariables error1 = new entVariables();
                error1.NombreInput = "DDLIDVariable";
                error1.MensajeError = "";
                error1.EstilosError = "1px solid #ccc";

                lstErrores.Add(error1);
            }

            if (items.DatoTipo == "- Seleccione -")
            {
                entVariables error1 = new entVariables();
                error1.NombreInput = "DDLTipoDato";
                error1.MensajeError = "El campo nombre es requerido";
                error1.EstilosError = "1px solid #FF0000";

                lstErrores.Add(error1);
            }
            else
            {
                entVariables error1 = new entVariables();
                error1.NombreInput = "DDLTipoDato";
                error1.MensajeError = "";
                error1.EstilosError = "1px solid #ccc";

                lstErrores.Add(error1);
            }


            return Json(new { Success = success, Mensaje = "<center>Faltan campos por capturar.</center>", Error = lstErrores });
        }


    }

Model

    public class entVariables
{
    /*Propiedades Variable*/
    [Required]
    public string VariableNombre { get; set; }
    [Required]
    public int IdVariableIdentificador { get; set; }
    public string ValorVariableIdentificador { get; set; }
    public int IDDatoTipo { get; set; }
    [Required]
    public string DatoTipo { get; set; }
    public int NumeroDecimales { get; set; }
    public int ValorConstante { get; set; }
    public decimal ValorMinimo { get; set; }
    public decimal ValorMaximo { get; set; }
    public decimal ValorIncremento { get; set; }
    public string NombreInput { get; set; }
    public string MensajeError { get; set; }
    public string EstilosError { get; set; }
    public int IDNuevaVariable { get; set; }
}
    
asked by Ivxn 13.04.2018 в 00:33
source

2 answers

1

It will always happen to you with properties of the type int . By not passing any value (the zero would be by default) in the post you are surely assigning null which for a property of type int causes the "required" which is native.

For this I can think of two quick solutions.

  • Assign 0 (zero) if the value in the view is not indicated.
  • Ignore validation, for the latter you can do it using [Bind (Exclude = {ProperName})]
  • Example:

    [HttpPost]        
    public ActionResult AgregarVariable([Bind(Exclude = "NumeroDecimales", "ValorConstante")] entVariables items)
    {
      //tu código...
    }
    

    I hope it serves you!

        
    answered by 17.04.2018 в 04:17
    1

    Another way is by modifying your model by adding? to the attribute you want, to indicate that null values are allowed. example:

    public int? ValorConstante { get; set; }
    

    in this way will let you through. Greetings

        
    answered by 26.06.2018 в 16:59