Jorge
Jorge

Reputation: 18237

handle if in a razor view

Is there a better way to accomplish this if condition using maybe ? operator

@if (!String.IsNullOrEmpty(Model.valores))
        {
            @crearContenedorTipo(
                Model.IDTipodato,
                Model.minimo, Model.maximo,
                Model.valores.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries),
                Model.salida, Model.IDCampo)
            @Html.ValidationMessageFor(modelItem => Model.Nombre)
        }
        else 
        { 
            @crearContenedorTipo(
                Model.IDTipodato,
                Model.minimo, Model.maximo,
                new string[] {},
                Model.salida, Model.IDCampo)
            @Html.ValidationMessageFor(modelItem => Model.Nombre)
        }

here's the signature of my helper

@helper crearContenedorTipo(int tipoDato, int? min, int? max, string[] valor, bool salida, int id)

Upvotes: 0

Views: 114

Answers (1)

driis
driis

Reputation: 164291

As I read your code, the if is only there to guard against a null or empty string. The rest of the block is the same, apart from the Model.valores argument. Therefore, this would be equivalent to your code:

@crearContenedorTipo(
                Model.IDTipodato,
                Model.minimo, Model.maximo,
                (Model.valores ?? String.Empty).Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries),
                Model.salida, Model.IDCampo)
            @Html.ValidationMessageFor(modelItem => Model.Nombre)

This works because of StringSplitOptions.RemoveEmptyEntries - when the string is empty, no items is returned.

Upvotes: 2

Related Questions