Rogerio Azevedo
Rogerio Azevedo

Reputation: 794

Validate Required on Non Model MVC Dropdownlist

I have a Dropdownlist from a Viewbag and I need to validate it like "Required"

My Controller

public ActionResult EsperaPorHora()
        {
            var cliente = new UsuarioData().Id_LicenciadoPorId(User.Identity.GetUserId());
            var Cli = !string.IsNullOrEmpty(cliente.ToString()) ? Convert.ToInt32(cliente) : 0;
            var cliData = new LicenciadoData();
            var agora = DateTime.Now;
            ViewBag.Data1 = agora.ToShortDateString();
            ViewBag.Data2 = agora.ToShortDateString();

            if (Cli != 0)
            {
                ViewBag.IdCliente = new SelectList(cliData.ListaClienteId(Cli), "Id", "Fantasia");
            }
            else
            {
                ViewBag.IdCliente = new SelectList(cliData.ListarClientes(), "Id", "Fantasia");
            }           
            return View();
        }

        [HttpGet]
        public JsonResult EsperaHora(string data1, string data2, int? cliente)
        {
            var voiceData = new KiperVoiceData(cliente);
            var media = voiceData.GetEsperaData(data1, data2);
            var atend = voiceData.GetEsperaHora(data1, data2);

            var result = new { atend, media };
            return Json(result, JsonRequestBehavior.AllowGet);
        }

I tried:

@Html.DropDownList("IdCliente", null, "SELECIONE A EMPRESA", htmlAttributes: new { @class = "form-control combo2", @required = "required" })                              

@Html.DropDownList("IdCliente", null, "SELECIONE A EMPRESA", htmlAttributes: new { @class = "form-control combo2", @required = true })                              

@Html.DropDownList("IdCliente", null, "SELECIONE A EMPRESA", htmlAttributes: new { @class = "form-control combo2", required = true })  

But no one worked to me, if I click button without select it run to an exception. What im doing wrong?

Upvotes: 0

Views: 3651

Answers (2)

Rogerio Azevedo
Rogerio Azevedo

Reputation: 794

Solve the situation on html and razor is important, primarily to improve my knowledge. As I told above, I could find a solution using Js and a component named Sweet Alert as follow:

var data1 = $('#data1').val();
var data2 = $('#data2').val();
var cliente = $('#IdCliente option:selected').val();

if (cliente != "") {

            $.ajax({
                url: '',
                dataType: "json",
                type: "GET",
                data: { 'data1': data1, 'data2': data2, 'cliente': cliente },
                success: function (data) {
                    }
                },

                error: function (xhr) {
                    alert('error');
                }
            });
        }
        else {
            swal({ type: "warning", title: "Alerta", text: "Selecione uma empresa por favor!", timer: 5000, showConfirmButton: true });
        }

This is the result:

Alert Sweet

Upvotes: 0

CodingYoshi
CodingYoshi

Reputation: 26989

Send the required as a class like this:

Update

Use an overload with optionlabel. I am passing "choose" here, but you can pass whatever you need. Also put a validation summary to inform the user it is a required field.

@Html.ValidationSummary()
 @Html.DropDownList("name", new List<SelectListItem> { new SelectListItem { Text = "1", Value = "2" } }, "choose", htmlAttributes: new { @class = "form-control combo2 required", @data_val = "true", @data_val_required = "choose is a required field" })                    

Upvotes: 2

Related Questions